码迷,mamicode.com
首页 > 数据库 > 详细

Python 连接数据库

时间:2018-04-27 13:51:20      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:res   mysq   def   database   fetchall   encoding   close   resultset   comm   

python2

  • 使用MySQLdb即可
  • 代码如下

    class sql(object):
        def __init__(self):
            try:
                self.conn = MySQLdb.connect(
                    host=DB_IP,
                    user=DB_USER,
                    passwd=DB_PASSWORD,
                    db=DB_NAME,
                )
                self.conn.set_character_set(‘utf8‘)
                self.cur = self.conn.cursor()
                self.cur.execute(‘SET NAMES utf8;‘)
                self.cur.execute(‘SET CHARACTER SET utf8;‘)
                self.cur.execute(‘SET character_set_connection=utf8;‘)
            except Exception as e:
                raise e
        # 返回二维元组,每一条记录作为一个元组,所有的记录再组成一个元组
        def executeQuery(self, sqlcode):
            try:
                self.cur.execute(sqlcode)
                resultSet = self.cur.fetchall()
                self.conn.commit()
                return resultSet
            except Exception as e:
                self.conn.rollback()
                raise e
        def executeUpdate(self, sqlCode):
            try:
                self.cur.execute(sqlCode)
                self.conn.commit()
            except Exception as e:
                self.conn.rollback()
                raise e
        def __del__(self):
            self.conn.close()

    python3

  • 使用pymysql

    db=pymysql.connect(host="192.168.1.102",user="root",password="123456",database="fwwb",charset=‘utf8‘)
    cursor = db.cursor()
    当参数比较多时要指定参数名,不然会报错
  • 当查询结果中含有中文时要指定charset参数,不然会出现乱码
  • 将结果写入文档时open函数要添加encoding参数指定编码
  • 查询

    results = cursor.fetchall() #返回所有结果
    data = cursor.fetchone() #返回单条数据

Python 连接数据库

标签:res   mysq   def   database   fetchall   encoding   close   resultset   comm   

原文地址:https://www.cnblogs.com/l-h-x/p/8961789.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!