本文针对 Python 操作 MySQL 主要使用的两种方式讲解:
- 原生模块 pymsql
- ORM框架 SQLAchemy
本章内容:
- pymsql 执行 sql 增\删\改\查 语句
- pymsql 获取查询内容、获取自增 ID
- pymsql 游标
- pymsql 更改 fetch 数据类型
- pymsql 利用 with 简化操作
- ORM 下载安装
- ORM 史上最全操作
一、pymsql
pymsql 是 Python 中操作 MySQL 的原生模块,其使用方法和 MySQL 的SQL语句几乎相同
1、下载安装
pip3 install pymysql
2、执行SQL
执行 SQL 语句的基本语法:
需要注意的是:创建链接后,都由游标来进行与数据库的操作,当然,拿到数据也靠游标
#!/usr/bin/env python # -*- coding:utf-8 -*- import pymysql # 创建连接 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1') # 创建游标 cursor = conn.cursor() # 执行SQL,并返回收影响行数 effect_row = cursor.execute("update hosts set host = '1.1.1.2'") # 执行SQL,并返回受影响行数 #effect_row = cursor.execute("update hosts set host = '1.1.1.2' where nid > %s", (1,)) # 执行SQL,并返回受影响行数 #effect_row = cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)]) # 提交,不然无法保存新建或者修改的数据 conn.commit() # 关闭游标 cursor.close() # 关闭连接 conn.close()
3、获取新创建数据自增ID
可以获取到最新自增的ID,也就是最后插入的一条数据ID
#!/usr/bin/env python # -*- coding:utf-8 -*- import pymysql conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1') cursor = conn.cursor() cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)]) conn.commit() cursor.close() conn.close() # 获取最新自增ID new_id = cursor.lastrowid
4、获取查询数据
获取查询数据的三种方式:
#!/usr/bin/env python # -*- coding:utf-8 -*- import pymysql conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1') cursor = conn.cursor() cursor.execute("select * from hosts") # 获取第一行数据 row_1 = cursor.fetchone() # 获取前n行数据 # row_2 = cursor.fetchmany(3) # 获取所有数据 # row_3 = cursor.fetchall() conn.commit() cursor.close() conn.close()
5、移动游标
操作都是靠游标,那对游标的控制也是必须的
注:在fetch数据时按照顺序进行,可以使用cursor.scroll(num,mode)来移动游标位置,如: cursor.scroll(1,mode='relative') # 相对当前位置移动 cursor.scroll(2,mode='absolute') # 相对绝对位置移动
6、fetch数据类型
默认拿到的数据是小括号,元祖类型,如果是字典的话会更方便操作,那方法来了:
# 关于默认获取的数据是元祖类型,如果想要或者字典类型的数据,即: #!/usr/bin/env python # -*- coding:utf-8 -*- import pymysql conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1') # 游标设置为字典类型 cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) r = cursor.execute("call p1()") result = cursor.fetchone() conn.commit() cursor.close() conn.close()
7、利用 with 自动关闭
每次连接数据库都需要连接和关闭,啊,好多代码,那么方法又来了:
是不是很屌啊?
# 利用with定义函数 @contextlib.contextmanager def mysql(self, host='127.0.0.1', port=3306, user='nick', passwd='', db='db1', charset='utf8'): self.conn = pymysql.connect(host=host, port=port, user=user, passwd=passwd, db=db, charset=charset) self.cuersor = self.conn.cursor(cursor=pymysql.cursors.DictCursor) try: yield self.cuersor finally: self.conn.commit() self.cuersor.close() self.conn.close() # 执行 with mysql() as cuersor: print(cuersor) # 操作MySQL代码块
二、SQLAlchemy
SQLAlchemy 简称 ORM 框架,该框架建立在数据库的 API 之上,使用关系对象映射来进行数据库操作;
简言之便是:将类对象转换成 SQL 语句,然后使用数据 API 执行 SQL 语句并获取执行结果。
1、下载安装
pip3 install SQLAlchemy
需要注意了:SQLAlchemy 自己无法操作数据库,必须结合 pymsql 等第三方插件,Dialect 用于和数据 API 进行交互,根据配置文件的不同调用不同的数据库 API,从而实现对数据库的操作,如:
MySQL-Python mysql+mysqldb://<user>:<password>@<host>[:<port>]/<dbname> pymysql mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>] MySQL-Connector mysql+mysqlconnector://<user>:<password>@<host>[:<port>]/<dbname> cx_Oracle oracle+cx_oracle://user:pass@host:port/dbname[?key=value&key=value...] 更多详见:http://docs.sqlalchemy.org/en/latest/dialects/index.html
2、内部处理
使用 Engine/ConnectionPooling/Dialect 进行数据库操作,Engine使用ConnectionPooling连接数据库,然后再通过Dialect执行SQL语句。
#!/usr/bin/env python # -*- coding:utf-8 -*- from sqlalchemy import create_engine engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/t1", max_overflow=5) # 执行SQL # cur = engine.execute( # "INSERT INTO hosts (host, color_id) VALUES ('1.1.1.22', 3)" # ) # 新插入行自增ID # cur.lastrowid # 执行SQL # cur = engine.execute( # "INSERT INTO hosts (host, color_id) VALUES(%s, %s)",[('1.1.1.22', 3),('1.1.1.221', 3),] # ) # 执行SQL # cur = engine.execute( # "INSERT INTO hosts (host, color_id) VALUES (%(host)s, %(color_id)s)", # host='1.1.1.99', color_id=3 # ) # 执行SQL # cur = engine.execute('select * from hosts') # 获取第一行数据 # cur.fetchone() # 获取第n行数据 # cur.fetchmany(3) # 获取所有数据 # cur.fetchall()