python 之操作mysql 数据库实例

对于python操作mysql 数据库,具体的步骤应为:

1. 连接上mysql host 端口号 数据库 账号 密码
2. 建立游标
3. 执行sql(注意,如果是update,insert,delete 需要进行提交才能生效。)
4. 获取结果
5. 关闭连接、关闭游标

一、默认获取的结果是元祖

 1 conn = pymysql.connect(host='localhost',user='root',passwd='123456',port=3306,db='sakila',charset='utf8')
 2 #charset 必须写utf8, 不能写utf-8; port 要写int 类型,不能加上引号
 3 cur = conn.cursor() # 建立游标,游标认为你是仓库管理员
 4 cur.execute('select * from user limit 10;')
 5 res = cur.fetchone() # 只获取一条结果,它的结果是一个一维元祖,第一次获取到第一条
 6 ##print('fetchone',cur.fetchone()) # 第二次获取到的是第二行;
 7 print(res)
 8 print('fetchall',cur.fetchall())# 获取第二条开始的所有数据,获取sql语句执行的结果, 是个二维元祖,它把结果放到一个元祖里,每一条数据也是一个元祖
 9 print(res)
10 print(res[0][1])
11 print('fetchone',cur.fetchone()) # #被获取完了,所以获取到的是None
12 # 如果确定只有一条数据的用fetchone, 超过一条数据的那就用fetchall

二、将获取的结果转字典,方便使用

1 conn = pymysql.connect(host='localhost',user='root',passwd='123456',port=3306,db='sakila',charset='utf8')
2 cur = conn.cursor(cursor=pymysql.cursors.DictCursor) # 将元祖转为字典
3 sql = "select * from user where name='aa'"
4 cur.execute(sql)
5 print(cur.fetchone()) #获取字典
6 res = cur.fetchall()
7 print(res) #list 里存字典
8 cur.close()#关闭游标
9 conn.close()#关闭连接

在python 中会经常用到mysql,因此可以写了一个函数用于mysql的操作,要使用时调用以下即可。

 1 import pymysql
 2 def op_mysql(host,user,password,db,sql,port=3306,charset='utf8'):
 3     conn = pymysql.connect(host=host,user=user,
 4                            password=password,
 5                            db=db,
 6                            port=port,
 7                            charset=charset)
 8     cur = conn.cursor(cursor=pymysql.cursors.DictCursor)
 9     cur.execute(sql)
10     # select, update, delete, insert 长度都是6位
11     # SELECT
12     sql_start = sql[:6].upper() # sql 的前6位字符串,判断它是什么类型的sql语句
13     if sql_start == 'SELECT':
14         res = cur.fetchall()
15     else:
16         conn.commit()
17         res = 'ok'
18     cur.close()
19     conn.close()
20     return res
21 sql = 'select * from user limit 5;'
22 op_mysql(
23         host='localhost',
24         user='root',
25         password='123456',
26         port=3306,
27         db='sakila',
28         charset='utf8',
29         sql=sql)