如何在Python中操作MySQL

一. python操作数据库介绍

Python 标准数据库接口为 Python DB-API,Python DB-API为开发人员提供了数据库应用编程接口。Python 数据库接口支持非常多的数据库,你可以选择适合你项目的数据库:

  • GadFly
  • mSQL
  • MySQL
  • PostgreSQL
  • Microsoft SQL Server 2000
  • Informix
  • Interbase
  • Oracle
  • Sybase ...

你可以访问Python数据库接口及API查看详细的支持数据库列表。

不同的数据库你需要下载不同的DB API模块,例如你需要访问Oracle数据库和Mysql数据,你需要下载Oracle和MySQL数据库模块。

DB-API 是一个规范. 它定义了一系列必须的对象和数据库存取方式, 以便为各种各样的底层数据库系统和多种多样的数据库接口程序提供一致的访问接口 。

Python的DB-API,为大多数的数据库实现了接口,使用它连接各数据库后,就可以用相同的方式操作各数据库。

Python DB-API使用流程:

  • 引入 API 模块。
  • 获取与数据库的连接。
  • 执行SQL语句和存储过程。
  • 关闭数据库连接。

二. python操作MySQL模块

Python操作MySQL主要使用两种方式:

  1. DB模块(原生SQL)

    • PyMySQL(支持python2.x/3.x)
    • MySQLdb(目前仅支持python2.x)
  2. ORM框架

    • SQLAchemy

2.1 PyMySQL模块

本文主要介绍PyMySQL模块,MySQLdb使用方式类似

2.1.1 安装PyMySQL

PyMySQL是一个Python编写的MySQL驱动程序,让我们可以用Python语言操作MySQL数据库。

pip install PyMySQL 

2.2 基本使用



1.  #! /usr/bin/env python
    
2.  # -*- coding: utf-8 -*-
    
3.  # __author__ = "shuke"
    
4.  # Date: 2018/5/13
    

6.  import pymysql
    

8.  # 创建连接
    
9.  conn = pymysql.connect(host="127.0.0.1", port=3306, user='zff', passwd='zff123', db='zff', charset='utf8mb4')
    

11.  # 创建游标(查询数据返回为元组格式)
    
12.  # cursor = conn.cursor()
    

14.  # 创建游标(查询数据返回为字典格式)
    
15.  cursor = conn.cursor(pymysql.cursors.DictCursor)
    

17.  # 1. 执行SQL,返回受影响的行数
    
18.  effect_row1 = cursor.execute("select * from USER")
    

20.  # 2. 执行SQL,返回受影响的行数,一次插入多行数据
    
21.  effect_row2 = cursor.executemany("insert into USER (NAME) values(%s)", [("jack"), ("boom"), ("lucy")])  # 3
    

23.  # 查询所有数据,返回数据为元组格式
    
24.  result = cursor.fetchall()
    

26.  # 增/删/改均需要进行commit提交,进行保存
    
27.  conn.commit()
    

29.  # 关闭游标
    
30.  cursor.close()
    

32.  # 关闭连接
    
33.  conn.close()
    

35.  print(result)
    
36.  """
    
37.  [{'id': 6, 'name': 'boom'}, {'id': 5, 'name': 'jack'}, {'id': 7, 'name': 'lucy'}, {'id': 4, 'name': 'tome'}, {'id': 3, 'name': 'zff'}, {'id': 1, 'name': 'zhaofengfeng'}, {'id': 2, 'name': 'zhaofengfeng02'}]
    
38.  """
    

2.3 获取最新创建的数据自增ID



1.  #! /usr/bin/env python
    
2.  # -*- coding: utf-8 -*-
    
3.  # __author__ = "shuke"
    
4.  # Date: 2018/5/13
    

6.  import pymysql
    

8.  # 创建连接
    
9.  conn = pymysql.connect(host="127.0.0.1", port=3306, user='zff', passwd='zff123', db='zff', charset='utf8mb4')
    

11.  # 创建游标(查询数据返回为元组格式)
    
12.  cursor = conn.cursor()
    

14.  # 获取新创建数据自增ID
    
15.  effect_row = cursor.executemany("insert into USER (NAME)values(%s)", [("eric")])
    

17.  # 增删改均需要进行commit提交
    
18.  conn.commit()
    

20.  # 关闭游标
    
21.  cursor.close()
    

23.  # 关闭连接
    
24.  conn.close()
    

26.  new_id = cursor.lastrowid
    
27.  print(new_id)
    
28.  """
    
29.  8
    
30.  """
    

2.4 查询操作



1.  #! /usr/bin/env python
    
2.  # -*- coding: utf-8 -*-
    
3.  # __author__ = "shuke"
    
4.  # Date: 2018/5/13
    

6.  import pymysql
    

8.  # 创建连接
    
9.  conn = pymysql.connect(host="127.0.0.1", port=3306, user='zff', passwd='zff123', db='zff', charset='utf8mb4')
    

11.  # 创建游标
    
12.  cursor = conn.cursor()
    

14.  cursor.execute("select * from USER")
    

16.  # 获取第一行数据
    
17.  row_1 = cursor.fetchone()
    

19.  # 获取前n行数据
    
20.  row_2 = cursor.fetchmany(3)
    
21.  #
    
22.  # # 获取所有数据
    
23.  row_3 = cursor.fetchall()
    

25.  # 关闭游标
    
26.  cursor.close()
    

28.  # 关闭连接
    
29.  conn.close()
    
30.  print(row_1)
    
31.  print(row_2)
    
32.  print(row_3)
    

⚠️ 在fetch数据时按照顺序进行,可以使用cursor.scroll(num,mode)来移动游标位置,如:

  • cursor.scroll(1,mode='relative')  # 相对当前位置移动
  • cursor.scroll(2,mode='absolute')  # 相对绝对位置移动

2.5 防止SQL注入



1.  #! /usr/bin/env python
    
2.  # -*- coding: utf-8 -*-
    
3.  # __author__ = "shuke"
    
4.  # Date: 2018/5/13
    

6.  import pymysql
    

8.  # 创建连接
    
9.  conn = pymysql.connect(host="127.0.0.1", port=3306, user='zff', passwd='zff123', db='zff', charset='utf8mb4')
    

11.  # 创建游标
    
12.  cursor = conn.cursor()
    

14.  # 存在sql注入情况(不要用格式化字符串的方式拼接SQL)
    
15.  sql = "insert into USER (NAME) values('%s')" % ('zhangsan',)
    
16.  effect_row = cursor.execute(sql)
    

18.  # 正确方式一
    
19.  # execute函数接受一个元组/列表作为SQL参数,元素个数只能有1个
    
20.  sql = "insert into USER (NAME) values(%s)"
    
21.  effect_row1 = cursor.execute(sql, ['wang6'])
    
22.  effect_row2 = cursor.execute(sql, ('wang7',))
    

24.  # 正确方式二
    
25.  sql = "insert into USER (NAME) values(%(name)s)"
    
26.  effect_row1 = cursor.execute(sql, {'name': 'wudalang'})
    

28.  # 写入插入多行数据
    
29.  effect_row2 = cursor.executemany("insert into USER (NAME) values(%s)", [('ermazi'), ('dianxiaoer')])
    

31.  # 提交
    
32.  conn.commit()
    
33.  # 关闭游标
    
34.  cursor.close()
    
35.  # 关闭连接
    
36.  conn.close()
    

这样,SQL操作就更安全了。如果需要更详细的文档参考PyMySQL文档吧。不过好像这些SQL数据库的实现还不太一样,PyMySQL的参数占位符使用%s这样的C格式化符,而Python自带的sqlite3模块的占位符好像是问号(?)。因此在使用其他数据库的时候还是仔细阅读文档吧。Welcome to PyMySQL’s documentation

**很多人学习python,不知道从何学起。
很多人学习python,掌握了基本语法过后,不知道在哪里寻找案例上手。
很多已经做案例的人,却不知道如何去学习更加高深的知识。
那么针对这三类人,我给大家提供一个好的学习平台,免费领取视频教程,电子书籍,以及课程的源代码!**
QQ群:721195303

三. 数据库连接池

上文中的方式存在一个问题,单线程情况下可以满足,程序需要频繁的创建释放连接来完成对数据库的操作,那么,我们的程序/脚本在多线程情况下会引发什么问题呢?此时,我们就需要使用数据库连接池来解决这个问题!

3.1 DBUtils模块

DBUtils是Python的一个用于实现数据库连接池的模块。

此连接池有两种连接模式:

  • 为每个线程创建一个连接,线程即使调用了close方法,也不会关闭,只是把连接重新放到连接池,供自己线程再次使用。当线程终止时,连接才会自动关闭
  • 创建一批连接到连接池,供所有线程共享使用(推荐使用)

3.2 模式一



1.  #! /usr/bin/env python
    
2.  # -*- coding: utf-8 -*-
    
3.  # __author__ = "shuke"
    
4.  # Date: 2018/5/13
    

6.  from DBUtils.PersistentDB import PersistentDB
    
7.  import pymysql
    

9.  POOL = PersistentDB(
    
10.      creator=pymysql,  # 使用链接数据库的模块
    
11.      maxusage=None,  # 一个链接最多被重复使用的次数,None表示无限制
    
12.      setsession=[],  # 开始会话前执行的命令列表。如:["set datestyle to ...", "set time zone ..."]
    
13.      ping=0,
    
14.      # ping MySQL服务端,检查是否服务可用。# 如:0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always
    
15.      closeable=False,
    
16.      # 如果为False时, conn.close() 实际上被忽略,供下次使用,再线程关闭时,才会自动关闭链接。如果为True时, conn.close()则关闭链接,那么再次调用pool.connection时就会报错,因为已经真的关闭了连接(pool.steady_connection()可以获取一个新的链接)
    
17.      threadlocal=None,  # 本线程独享值得对象,用于保存链接对象,如果链接对象被重置
    
18.      host='127.0.0.1',
    
19.      port=3306,
    
20.      user='zff',
    
21.      password='zff123',
    
22.      database='zff',
    
23.      charset='utf8',
    
24.  )
    

27.  def func():
    
28.      conn = POOL.connection(shareable=False)
    
29.      cursor = conn.cursor()
    
30.      cursor.execute('select * from USER')
    
31.      result = cursor.fetchall()
    
32.      cursor.close()
    
33.      conn.close()
    
34.      return result
    

37.  result = func()
    
38.  print(result)
    

3.2 模式二



1.  #! /usr/bin/env python
    
2.  # -*- coding: utf-8 -*-
    
3.  # __author__ = "shuke"
    
4.  # Date: 2018/5/13
    

6.  import time
    
7.  import pymysql
    
8.  import threading
    
9.  from DBUtils.PooledDB import PooledDB, SharedDBConnection
    

11.  POOL = PooledDB(
    
12.      creator=pymysql,  # 使用链接数据库的模块
    
13.      maxconnections=6,  # 连接池允许的最大连接数,0和None表示不限制连接数
    
14.      mincached=2,  # 初始化时,链接池中至少创建的空闲的链接,0表示不创建
    
15.      maxcached=5,  # 链接池中最多闲置的链接,0和None不限制
    
16.      maxshared=3,
    
17.      # 链接池中最多共享的链接数量,0和None表示全部共享。PS: 无用,因为pymysql和MySQLdb等模块的 threadsafety都为1,所有值无论设置为多少,_maxcached永远为0,所以永远是所有链接都共享。
    
18.      blocking=True,  # 连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错
    
19.      maxusage=None,  # 一个链接最多被重复使用的次数,None表示无限制
    
20.      setsession=[],  # 开始会话前执行的命令列表。如:["set datestyle to ...", "set time zone ..."]
    
21.      ping=0,
    
22.      # ping MySQL服务端,检查是否服务可用。# 如:0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always
    
23.      host='127.0.0.1',
    
24.      port=3306,
    
25.      user='zff',
    
26.      password='zff123',
    
27.      database='zff',
    
28.      charset='utf8'
    
29.  )
    

32.  def func():
    
33.      # 检测当前正在运行连接数的是否小于最大链接数,如果不小于则:等待或报raise TooManyConnections异常
    
34.      # 否则
    
35.      # 则优先去初始化时创建的链接中获取链接 SteadyDBConnection。
    
36.      # 然后将SteadyDBConnection对象封装到PooledDedicatedDBConnection中并返回。
    
37.      # 如果最开始创建的链接没有链接,则去创建一个SteadyDBConnection对象,再封装到PooledDedicatedDBConnection中并返回。
    
38.      # 一旦关闭链接后,连接就返回到连接池让后续线程继续使用。
    
39.      conn = POOL.connection()
    

41.      # print('连接被拿走了', conn._con)
    
42.      # print('池子里目前有', POOL._idle_cache, 'rn')
    

44.      cursor = conn.cursor()
    
45.      cursor.execute('select * from USER')
    
46.      result = cursor.fetchall()
    
47.      conn.close()
    
48.      return result
    

51.  result = func()
    
52.  print(result)
    

⚠️ 由于pymysql、MySQLdb等threadsafety值为1,所以该模式连接池中的线程会被所有线程共享,因此是线程安全的。如果没有连接池,使用pymysql来连接数据库时,单线程应用完全没有问题,但如果涉及到多线程应用那么就需要加锁,一旦加锁那么连接势必就会排队等待,当请求比较多时,性能就会降低了。

3.3 加锁



1.  #! /usr/bin/env python
    
2.  # -*- coding: utf-8 -*-
    
3.  # __author__ = "shuke"
    
4.  # Date: 2018/5/13
    

6.  import pymysql
    
7.  import threading
    
8.  from threading import RLock
    

10.  LOCK = RLock()
    
11.  CONN = pymysql.connect(host='127.0.0.1',
    
12.                         port=3306,
    
13.                         user='zff',
    
14.                         password='zff123',
    
15.                         database='zff',
    
16.                         charset='utf8')
    

19.  def task(arg):
    
20.      with LOCK:
    
21.          cursor = CONN.cursor()
    
22.          cursor.execute('select * from USER ')
    
23.          result = cursor.fetchall()
    
24.          cursor.close()
    

26.          print(result)
    

29.  for i in range(10):
    
30.      t = threading.Thread(target=task, args=(i,))
    
31.      t.start()
    

3.4 无锁(报错)



1.  #! /usr/bin/env python
    
2.  # -*- coding: utf-8 -*-
    
3.  # __author__ = "shuke"
    
4.  # Date: 2018/5/13
    

6.  import pymysql
    
7.  import threading
    

9.  CONN = pymysql.connect(host='127.0.0.1',
    
10.                         port=3306,
    
11.                         user='zff',
    
12.                         password='zff123',
    
13.                         database='zff',
    
14.                         charset='utf8')
    

17.  def task(arg):
    
18.      cursor = CONN.cursor()
    
19.      cursor.execute('select * from USER ')
    
20.      # cursor.execute('select sleep(10)')
    
21.      result = cursor.fetchall()
    
22.      cursor.close()
    
23.      print(result)
    

26.  for i in range(10):
    
27.      t = threading.Thread(target=task, args=(i,))
    
28.      t.start()
    

此时可以在数据库中查看连接情况: show status like 'Threads%';

四. 数据库连接池结合pymsql使用



1.  # cat sql_helper.py
    

3.  import pymysql
    
4.  import threading
    
5.  from DBUtils.PooledDB import PooledDB, SharedDBConnection
    
6.  POOL = PooledDB(
    
7.      creator=pymysql,  # 使用链接数据库的模块
    
8.      maxconnections=20,  # 连接池允许的最大连接数,0和None表示不限制连接数
    
9.      mincached=2,  # 初始化时,链接池中至少创建的空闲的链接,0表示不创建
    
10.      maxcached=5,  # 链接池中最多闲置的链接,0和None不限制
    
11.      #maxshared=3,  # 链接池中最多共享的链接数量,0和None表示全部共享。PS: 无用,因为pymysql和MySQLdb等模块的 threadsafety都为1,所有值无论设置为多少,_maxcached永远为0,所以永远是所有链接都共享。
    
12.      blocking=True,  # 连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错
    
13.      maxusage=None,  # 一个链接最多被重复使用的次数,None表示无限制
    
14.      setsession=[],  # 开始会话前执行的命令列表。如:["set datestyle to ...", "set time zone ..."]
    
15.      ping=0,
    
16.      # ping MySQL服务端,检查是否服务可用。# 如:0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always
    
17.      host='192.168.11.38',
    
18.      port=3306,
    
19.      user='root',
    
20.      passwd='apNXgF6RDitFtDQx',
    
21.      db='m2day03db',
    
22.      charset='utf8'
    
23.  )
    

26.  def connect():
    
27.      # 创建连接
    
28.      # conn = pymysql.connect(host='192.168.11.38', port=3306, user='root', passwd='apNXgF6RDitFtDQx', db='m2day03db')
    
29.      conn = POOL.connection()
    
30.      # 创建游标
    
31.      cursor = conn.cursor(pymysql.cursors.DictCursor)
    

33.      return conn,cursor
    

35.  def close(conn,cursor):
    
36.      # 关闭游标
    
37.      cursor.close()
    
38.      # 关闭连接
    
39.      conn.close()
    

41.  def fetch_one(sql,args):
    
42.      conn,cursor = connect()
    
43.      # 执行SQL,并返回收影响行数
    
44.      effect_row = cursor.execute(sql,args)
    
45.      result = cursor.fetchone()
    
46.      close(conn,cursor)
    

48.      return result
    

50.  def fetch_all(sql,args):
    
51.      conn, cursor = connect()
    

53.      # 执行SQL,并返回收影响行数
    
54.      cursor.execute(sql,args)
    
55.      result = cursor.fetchall()
    

57.      close(conn, cursor)
    
58.      return result
    

60.  def insert(sql,args):
    
61.      """
    
62.   创建数据
    
63.   :param sql: 含有占位符的SQL
    
64.   :return:
    
65.   """
    
66.      conn, cursor = connect()
    

68.      # 执行SQL,并返回收影响行数
    
69.      effect_row = cursor.execute(sql,args)
    
70.      conn.commit()
    

72.      close(conn, cursor)
    

74.  def delete(sql,args):
    
75.      """
    
76.   创建数据
    
77.   :param sql: 含有占位符的SQL
    
78.   :return:
    
79.   """
    
80.      conn, cursor = connect()
    

82.      # 执行SQL,并返回收影响行数
    
83.      effect_row = cursor.execute(sql,args)
    

85.      conn.commit()
    

87.      close(conn, cursor)
    

89.      return effect_row
    

91.  def update(sql,args):
    
92.      conn, cursor = connect()
    

94.      # 执行SQL,并返回收影响行数
    
95.      effect_row = cursor.execute(sql, args)
    

97.      conn.commit()
    

99.      close(conn, cursor)
    

101.      return effect_row
    

PS: 可以利用静态方法封装到一个类中,方便使用

在这里还是要推荐下我自己建的Python学习群:721195303,群里都是学Python的,如果你想学或者正在学习Python ,欢迎你加入,大家都是软件开发党,不定期分享干货(只有Python软件开发相关的),包括我自己整理的一份2021最新的Python进阶资料和零基础教学,欢迎进阶中和对Python感兴趣的小伙伴加入!

评论

暂无评论