Python 连接数据库

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() #返回单条数据

猜你喜欢

转载自www.cnblogs.com/l-h-x/p/8961789.html