目录:
- 安装
- 使用
一、安装
本模块为python第三方模块,需要单独安装。作用为调用mysql接口执行模块
pip3 install pyMySql
二、使用
1、执行SQL
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 import pymysql 4 5 # 创建连接 6 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1') 7 # 创建游标 8 cursor = conn.cursor() 9 10 # 执行SQL,并返回收影响行数 11 effect_row = cursor.execute("update hosts set host = '1.1.1.2'") 12 13 # 执行SQL,并返回受影响行数 14 #effect_row = cursor.execute("update hosts set host = '1.1.1.2' where nid > %s", (1,)) 15 16 # 执行SQL,并返回受影响行数 17 #effect_row = cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)]) 18 19 20 # 提交,不然无法保存新建或者修改的数据 21 conn.commit() 22 23 # 关闭游标 24 cursor.close() 25 # 关闭连接 26 conn.close()
2、获取新创建数据自增ID
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 import pymysql 4 5 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1') 6 cursor = conn.cursor() 7 cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)]) 8 conn.commit() 9 cursor.close() 10 conn.close() 11 12 # 获取最新自增ID 13 new_id = cursor.lastrowid
3、获取查询数据
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 import pymysql 4 5 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1') 6 cursor = conn.cursor() 7 cursor.execute("select * from hosts") 8 9 # 获取第一行数据 10 row_1 = cursor.fetchone() 11 12 # 获取前n行数据 13 # row_2 = cursor.fetchmany(3) 14 # 获取所有数据 15 # row_3 = cursor.fetchall() 16 17 conn.commit() 18 cursor.close() 19 conn.close()
注:在fetch数据时按照顺序进行,可以使用cursor.scroll(num,mode)来移动游标位置,如:
- cursor.scroll(1,mode='relative') # 相对当前位置移动
- cursor.scroll(2,mode='absolute') # 相对绝对位置移动
4、fetch数据类型
关于默认获取的数据是元祖类型,如果想要或者字典类型的数据,即:
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 import pymysql 4 5 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1') 6 7 # 游标设置为字典类型 8 cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) 9 r = cursor.execute("call p1()") 10 11 result = cursor.fetchone() 12 13 conn.commit() 14 cursor.close() 15 conn.close()