标签:res mysq def database fetchall encoding close resultset comm
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()
使用pymysql
db=pymysql.connect(host="192.168.1.102",user="root",password="123456",database="fwwb",charset=‘utf8‘)
cursor = db.cursor()
charset
参数,不然会出现乱码encoding
参数指定编码查询
results = cursor.fetchall() #返回所有结果
data = cursor.fetchone() #返回单条数据
标签:res mysq def database fetchall encoding close resultset comm
原文地址:https://www.cnblogs.com/l-h-x/p/8961789.html