Python学习之==>操做MySQL

1、简介:mysql

  MySQL为关系型数据库,其余关系型数据库包括Oracle、DB二、Sql Server等等。Python操做MySQL须要使用到pymsyql模块,pip安装便可。sql

2、操做MySQL步骤数据库

  一、连上数据库(IP、端口号、用户名、密码、数据库名)数组

  二、创建游标函数

  三、执行sqlfetch

  四、获取结果spa

  五、关闭游标excel

  六、关闭链接code

 1 import pymysql  2 conn = pymysql.connect(  3     host='192.168.1.112',  4     user='test',  5     passwd='111111',  6     port=3306,          # port必须是int类型
 7     db='test',  8     charset='utf8'      # charset必须写utf8,不能写utf-8
 9 ) 10 sqla = 'select * from stu limit 10;'
11 sqlb = 'insert into stu (id,name,sex) VALUE (10000,"张流量","女");'
12 cur = conn.cursor()     # 创建游标,不指定cursor类型返回的是二维元组
13 cur = conn.cursor(cursor=pymysql.cursors.DictCursor)  # 创建游标,指定cursor类型返回的是字典
14 cur.execute(sqla)       # 执行sqla
15 cur.execute(sqlb)       # 执行sqlb
16 conn.commit()           # 执行insert、delete、update语句必须commit
17 res = cur.fetchall()    # 执行全部返回的结果,fetchall返回的是一个二维数组
18 res = cur.fetchone()    # 执行全部返回的结果,fetchone返回的是第一行
19 res = cur.fetchmany(2)  # 执行全部返回的结果,fetchmany传入一个数返回多少条数据
20 res = cur.description   # 返回表中每一个字段的信息,description返回的也是一个二维数组
21 print(res) 22 cur.close()             # 关闭游标
23 conn.close()            # 关闭链接

 Cursor类型:blog

  不指定cursor类型,即:cur = conn.cursor(),则返回的结果是:((5, 'Ben', 男'), (6, 'Lily', 女')),是一个二维的元组

  指定curson类型,即:cur = conn.cursor(cursor=pymysql.cursors.DictCursor),则返回的结果是:

  [{'id': 5, 'name': 'Ben', 'sex': '男'}, {'id': 6, 'name': 'Lily', 'sex': '女'}]

fetchall()和fetchone()的区别:

  fetchall():获取到这个sql执行的所有结果,它把数据库表中的每一行数据放到一个元组或字典里面

  fetchone():获取到这个sql执行的一条结果,它返回的只是一条数据

  若是sql语句执行的结果是多条数据的时候,那就用 fetchall(),若是能肯定sql执行的结果只有一条,那就用fetchone()

3、封装操做MySQL数据库的函数

 1 def my_db(sql,port=3306,charset='utf8'):  2     import pymysql  3     host,user,passwd,db = '192.168.1.112','test','111111','test'  # 定义变量
 4     conn = pymysql.connect(host=host,  5                            user=user,  6                            passwd=passwd,  7                            port=port,  8                            db=db,  9                            charset=charset) 10     cur = conn.cursor(cursor=pymysql.cursors.DictCursor)  # 创建游标,指定cursor类型返回的是字典
11     cur.execute(sql)     # 执行语句
12     if sql.strip().split()[0].upper() == 'SELECT':        # 判断sql语句是否以select开头
13         res = cur.fetchall() 14     else: 15  conn.commit() 16         res = 'OK'
17     cur.close()         # 关闭游标
18     conn.close()        # 关闭链接
19     return res

 4、练习

  传入一个表名,把全部数据导出,写入excel文件

 1 def export_excel(table_name):  2     import pymysql,xlwt  3     conn = pymysql.connect(  4         host='118.24.3.40',  5         user='jxz',  6         passwd='123456',  7         port=3306,  8         db='jxz',  9         charset='utf8') 10     sql = 'select * from %s;'%table_name 11     cur = conn.cursor()        # 创建游标,不指定cursor类型返回的是二维元组
12     cur.execute(sql)           # 执行sql
13     all_data = cur.fetchall()  # 获取表中全部数据
14     fileds = [filed[0] for filed in cur.description]  # 获取表的全部字段存入一个list里面
15     book = xlwt.Workbook()               # 新建一个excel
16     sheet = book.add_sheet('sheet1')     # 增长sheet页
17     for col,filed in enumerate(fileds): 18         sheet.write(0,col,filed)         # 将表头写入excel文件中的第一行
19     row = 1                 # 定义行数
20     for data in all_data:   # 控制行
21         for col,filed in enumerate(data):#控制列
22  sheet.write(row,col,filed) 23         row = row + 1       # 每次写完一行,行加1
24     book.save('%s.xls'%table_name)
相关文章
相关标签/搜索