Python操作Mysql的方式有两种:
1)python的第三种模块:pymysql
2)ORM框架
一、pymysql
1、下载安装
pip3 install pymysql
2、操作方法
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语句的操作区间(都是把sql语句以字符串的形式来写)===================== 11 12 # 执行SQL,并返回收影响行数 13 effect_row = cursor.execute("update hosts set host = '1.1.1.2'") 14 15 # 执行SQL,并返回受影响行数 16 #effect_row = cursor.execute("update hosts set host = '1.1.1.2' where nid > %s", (1,)) # 不可用Python中的字符串替换,否则会有漏洞 17 18 # 执行SQL,并返回受影响行数 19 #effect_row = cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)]) 20 21 ========sql语句的操作区间===================== 22 23 # 提交,不然无法保存新建或者修改的数据 24 conn.commit() 25 26 # 关闭游标 27 cursor.close() 28 # 关闭连接 29 conn.close()
3、获取新创建数据自增ID(数据库表的最新id值)
1 # 获取最新自增ID 2 new_id = cursor.lastrowid
4、获取查询数据--fetchone;fetchmany();fetchall
注:1)获取查询数据的结果为元组类型
2)在fetch数据时按照顺序进行,可以使用cursor.scroll(num,mode)来移动游标位置,如:
-
-
- cursor.scroll(1,mode='relative') # 相对当前位置移动
- cursor.scroll(2,mode='absolute') # 相对绝对位置移动
-
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()