python学习需要mysql_【Python学习】操作Mysql

一、简介:

MySQL为关系型数据库,其他关系型数据库包括Oracle、DB2、Sql Server等等。Python操作MySQL需要使用到pymsyql模块,pip安装即可。

二、操作MySQL步骤

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

2、建立游标

3、执行sql

4、获取结果

5、关闭游标

6、关闭连接

48304ba5e6f9fe08f3fa1abda7d326ab.png

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() # 关闭连接

48304ba5e6f9fe08f3fa1abda7d326ab.png

Cursor类型:

不指定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()

三、封装操作MySQL数据库的函数

48304ba5e6f9fe08f3fa1abda7d326ab.png

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

48304ba5e6f9fe08f3fa1abda7d326ab.png

四、练习

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

48304ba5e6f9fe08f3fa1abda7d326ab.png

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)

48304ba5e6f9fe08f3fa1abda7d326ab.png

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值