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

python_操作mysql

时间:2019-11-19 12:24:09      阅读:61      评论:0      收藏:0      [点我收藏+]

标签:charset   exe   字典   toc   sql错误   connect   code   man   close   

一、操作MySQL

 1 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   

原文地址:https://www.cnblogs.com/xumb/p/11883565.html

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