python_操作mysql
时间:2021-07-01 10:21:17
帮助过:3人阅读
def op_mysql(sql,many=
True):
2 db_info = {
‘user‘:
‘xmb‘,
‘password‘:
‘123456‘,
‘host‘:
‘127.0.0.0‘,
‘db‘:
‘xmb‘,
‘port‘:3306,
‘charset‘:
‘utf8‘,
‘autocommit‘:True}
3 try:
4 conn = pymysql.connect(**db_info)
#建立连接
5 except Exception as e:
6 print(
‘mysql连接失败‘,e)
7 return ‘mysql连接失败‘
8 cur = conn.cursor(pymysql.cursors.DictCursor)
#建立游标
9 try:
10 cur.execute(sql)
#执行sql
11 except Exception as e:
12 print(
‘sql错误,%s‘%
sql)
13 result =
‘sql错误,%s‘%
sql
14 else:
15 if many:
16 result = cur.fetchall()
#fetchall 返回的是类表
17 else:
18 result = cur.fetchone()
#fetchone 返回的是字典
19 finally:
20 cur.close()
21 conn.close()
22 return result
python_操作mysql
标签:charset exe 字典 toc sql错误 connect code man close