如何用Python操作MySQL

WBOY
發布: 2023-05-30 16:31:14
轉載
1760 人瀏覽過

一. 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主要使用兩種方式:

    ##DB模組(原生SQL)

  • PyMySQL(支援python2.x/3.x)

MySQLdb(目前僅支援python2.x)

ORM框架


SQLAchemy


#2.1 PyMySQL模組

本文主要介紹PyMySQL模組,MySQLdb使用方式類似


2.1.1 安裝PyMySQL
  • #PyMySQL是一個Python寫的MySQL驅動程序,讓我們可以用Python語言操作MySQL資料庫。

    pip install PyMySQL
    登入後複製
  • 2.2 基本上使用
  • #! /usr/bin/env python
    # -*- coding: utf-8 -*-
    # __author__ = "shuke"
    # Date: 2018/5/13
    import pymysql
    # 创建连接
    conn = pymysql.connect(host="127.0.0.1", port=3306, user='zff', passwd='zff123', db='zff', charset='utf8mb4')
    # 创建游标(查询数据返回为元组格式)
    # cursor = conn.cursor()
    # 创建游标(查询数据返回为字典格式)
    cursor = conn.cursor(pymysql.cursors.DictCursor)
    # 1. 执行SQL,返回受影响的行数
    effect_row1 = cursor.execute("select * from USER")
    # 2. 执行SQL,返回受影响的行数,一次插入多行数据
    effect_row2 = cursor.executemany("insert into USER (NAME) values(%s)", [("jack"), ("boom"), ("lucy")])# 3
    # 查询所有数据,返回数据为元组格式
    result = cursor.fetchall()
    # 增/删/改均需要进行commit提交,进行保存
    conn.commit()
    # 关闭游标
    cursor.close()
    # 关闭连接
    conn.close()
    print(result)
    """
    [{'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'}]
    """
    登入後複製

    2.3 取得最新建立的資料自增ID

  • #! /usr/bin/env python
    # -*- coding: utf-8 -*-
    # __author__ = "shuke"
    # Date: 2018/5/13
    import pymysql
    # 创建连接
    conn = pymysql.connect(host="127.0.0.1", port=3306, user='zff', passwd='zff123', db='zff', charset='utf8mb4')
    # 创建游标(查询数据返回为元组格式)
    cursor = conn.cursor()
    # 获取新创建数据自增ID
    effect_row = cursor.executemany("insert into USER (NAME)values(%s)", [("eric")])
    # 增删改均需要进行commit提交
    conn.commit()
    # 关闭游标
    cursor.close()
    # 关闭连接
    conn.close()
    new_id = cursor.lastrowid
    print(new_id)
    """
    8
    """
    登入後複製
2.4 查詢操作

#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "shuke"
# Date: 2018/5/13
import pymysql
# 创建连接
conn = pymysql.connect(host="127.0.0.1", port=3306, user='zff', passwd='zff123', db='zff', charset='utf8mb4')
# 创建游标
cursor = conn.cursor()
cursor.execute("select * from USER")
# 获取第一行数据
row_1 = cursor.fetchone()
# 获取前n行数据
row_2 = cursor.fetchmany(3)
#
# # 获取所有数据
row_3 = cursor.fetchall()
# 关闭游标
cursor.close()
# 关闭连接
conn.close()
print(row_1)
print(row_2)
print(row_3)
登入後複製
⚠️ 在fetch資料時依照順序進行,可以使用cursor.scroll(num,mode)來移動遊標位置,如:



cursor.scroll( 1,mode='relative')  # 相對目前位置移動


#cursor.scroll(2,mode='absolute')  # 相對絕對位置移動


#2.5 防止SQL注入


#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "shuke"
# Date: 2018/5/13
import pymysql
# 创建连接
conn = pymysql.connect(host="127.0.0.1", port=3306, user='zff', passwd='zff123', db='zff', charset='utf8mb4')
# 创建游标
cursor = conn.cursor()
# 存在sql注入情况(不要用格式化字符串的方式拼接SQL)
sql = "insert into USER (NAME) values('%s')" % ('zhangsan',)
effect_row = cursor.execute(sql)
# 正确方式一
# execute函数接受一个元组/列表作为SQL参数,元素个数只能有1个
sql = "insert into USER (NAME) values(%s)"
effect_row1 = cursor.execute(sql, ['wang6'])
effect_row2 = cursor.execute(sql, ('wang7',))
# 正确方式二
sql = "insert into USER (NAME) values(%(name)s)"
effect_row1 = cursor.execute(sql, {'name': 'wudalang'})
# 写入插入多行数据
effect_row2 = cursor.executemany("insert into USER (NAME) values(%s)", [('ermazi'), ('dianxiaoer')])
# 提交
conn.commit()
# 关闭游标
cursor.close()
# 关闭连接
conn.close()
登入後複製

這樣,SQL操作就更安全了。如果需要更詳細的文件參考PyMySQL文件。不過好像這些SQL資料庫的實作還不太一樣,PyMySQL的參數佔位符使用%s這樣的C格式化符,而Python自帶的sqlite3模組的佔位符好像是問號(?)。因此在使用其他資料庫的時候還是仔細閱讀文件吧。
  • 三.資料庫連線池

  • 上文中的方式存在一個問題,單執行緒情況下可以滿足,程式需要頻繁的創建釋放連線來完成對資料庫的操作,那麼,我們的程式/腳本在多執行緒情況下會引發什麼問題呢?此時,我們就需要使用資料庫連線池來解決這個問題!

  • 3.1 DBUtils模組

DBUtils是Python的一個用來實作資料庫連線池的模組。

此連接池有兩種連接模式:


#為每個執行緒建立一個連接,執行緒即使呼叫了close方法,也不會關閉,只是把連線重新放到連線池,供自己執行緒再次使用。當執行緒終止時,連線才會自動關閉


建立一批連接到連線池,供所有執行緒共享使用(建議使用)


3.2 模式一


#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "shuke"
# Date: 2018/5/13
from DBUtils.PersistentDB import PersistentDB
import pymysql
POOL = PersistentDB(
 creator=pymysql,# 使用链接数据库的模块
 maxusage=None,# 一个链接最多被重复使用的次数,None表示无限制
 setsession=[],# 开始会话前执行的命令列表。如:["set datestyle to ...", "set time zone ..."]
 ping=0,
 # 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
 closeable=False,
 # 如果为False时, conn.close() 实际上被忽略,供下次使用,再线程关闭时,才会自动关闭链接。如果为True时, conn.close()则关闭链接,那么再次调用pool.connection时就会报错,因为已经真的关闭了连接(pool.steady_connection()可以获取一个新的链接)
 threadlocal=None,# 本线程独享值得对象,用于保存链接对象,如果链接对象被重置
 host='127.0.0.1',
 port=3306,
 user='zff',
 password='zff123',
 database='zff',
 charset='utf8',
)
def func():
 conn = POOL.connection(shareable=False)
 cursor = conn.cursor()
 cursor.execute('select * from USER')
 result = cursor.fetchall()
 cursor.close()
 conn.close()
 return result
result = func()
print(result)
登入後複製

3.2 模式二

#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "shuke"
# Date: 2018/5/13
import time
import pymysql
import threading
from DBUtils.PooledDB import PooledDB, SharedDBConnection
POOL = PooledDB(
 creator=pymysql,# 使用链接数据库的模块
 maxconnections=6,# 连接池允许的最大连接数,0和None表示不限制连接数
 mincached=2,# 初始化时,链接池中至少创建的空闲的链接,0表示不创建
 maxcached=5,# 链接池中最多闲置的链接,0和None不限制
 maxshared=3,
 # 链接池中最多共享的链接数量,0和None表示全部共享。PS: 无用,因为pymysql和MySQLdb等模块的 threadsafety都为1,所有值无论设置为多少,_maxcached永远为0,所以永远是所有链接都共享。
 blocking=True,# 连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错
 maxusage=None,# 一个链接最多被重复使用的次数,None表示无限制
 setsession=[],# 开始会话前执行的命令列表。如:["set datestyle to ...", "set time zone ..."]
 ping=0,
 # 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
 host='127.0.0.1',
 port=3306,
 user='zff',
 password='zff123',
 database='zff',
 charset='utf8'
)
def func():
 # 检测当前正在运行连接数的是否小于最大链接数,如果不小于则:等待或报raise TooManyConnections异常
 # 否则
 # 则优先去初始化时创建的链接中获取链接 SteadyDBConnection。
 # 然后将SteadyDBConnection对象封装到PooledDedicatedDBConnection中并返回。
 # 如果最开始创建的链接没有链接,则去创建一个SteadyDBConnection对象,再封装到PooledDedicatedDBConnection中并返回。
 # 一旦关闭链接后,连接就返回到连接池让后续线程继续使用。
 conn = POOL.connection()
 # print('连接被拿走了', conn._con)
 # print('池子里目前有', POOL._idle_cache, 'rn')
 cursor = conn.cursor()
 cursor.execute('select * from USER')
 result = cursor.fetchall()
 conn.close()
 return result
result = func()
print(result)
登入後複製
###⚠️ 由於pymysql、MySQLdb等threadsafety值為1,所以該模式連接池中的線程會被所有線程共享,因此是線程安全的。如果沒有連接池,使用pymysql來連接資料庫時,單執行緒應用程式完全沒有問題,但如果涉及到多執行緒應用那麼就需要加鎖,一旦加鎖那麼連線勢必就會排隊等待,當請求比較多時,效能就會降低了。 #########3.3 加鎖######
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "shuke"
# Date: 2018/5/13
import pymysql
import threading
from threading import RLock
LOCK = RLock()
CONN = pymysql.connect(host='127.0.0.1',
port=3306,
user='zff',
password='zff123',
database='zff',
charset='utf8')
def task(arg):
 with LOCK:
 cursor = CONN.cursor()
 cursor.execute('select * from USER ')
 result = cursor.fetchall()
 cursor.close()
 print(result)
for i in range(10):
 t = threading.Thread(target=task, args=(i,))
 t.start()
登入後複製
###3.4 無鎖定(錯誤)######
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "shuke"
# Date: 2018/5/13
import pymysql
import threading
CONN = pymysql.connect(host='127.0.0.1',
port=3306,
user='zff',
password='zff123',
database='zff',
charset='utf8')
def task(arg):
 cursor = CONN.cursor()
 cursor.execute('select * from USER ')
 # cursor.execute('select sleep(10)')
 result = cursor.fetchall()
 cursor.close()
 print(result)
for i in range(10):
 t = threading.Thread(target=task, args=(i,))
 t.start()
登入後複製
###此時可以在資料庫中檢視連線情況: show status like 'Threads%';#########四.資料庫連線池結合pymsql使用######
# cat sql_helper.py
import pymysql
import threading
from DBUtils.PooledDB import PooledDB, SharedDBConnection
POOL = PooledDB(
 creator=pymysql,# 使用链接数据库的模块
 maxconnections=20,# 连接池允许的最大连接数,0和None表示不限制连接数
 mincached=2,# 初始化时,链接池中至少创建的空闲的链接,0表示不创建
 maxcached=5,# 链接池中最多闲置的链接,0和None不限制
 #maxshared=3,# 链接池中最多共享的链接数量,0和None表示全部共享。PS: 无用,因为pymysql和MySQLdb等模块的 threadsafety都为1,所有值无论设置为多少,_maxcached永远为0,所以永远是所有链接都共享。
 blocking=True,# 连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错
 maxusage=None,# 一个链接最多被重复使用的次数,None表示无限制
 setsession=[],# 开始会话前执行的命令列表。如:["set datestyle to ...", "set time zone ..."]
 ping=0,
 # 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
 host='192.168.11.38',
 port=3306,
 user='root',
 passwd='apNXgF6RDitFtDQx',
 db='m2day03db',
 charset='utf8'
)
def connect():
 # 创建连接
 # conn = pymysql.connect(host='192.168.11.38', port=3306, user='root', passwd='apNXgF6RDitFtDQx', db='m2day03db')
 conn = POOL.connection()
 # 创建游标
 cursor = conn.cursor(pymysql.cursors.DictCursor)
 return conn,cursor
def close(conn,cursor):
 # 关闭游标
 cursor.close()
 # 关闭连接
 conn.close()
def fetch_one(sql,args):
 conn,cursor = connect()
 # 执行SQL,并返回收影响行数
 effect_row = cursor.execute(sql,args)
 result = cursor.fetchone()
 close(conn,cursor)
 return result
def fetch_all(sql,args):
 conn, cursor = connect()
 # 执行SQL,并返回收影响行数
 cursor.execute(sql,args)
 result = cursor.fetchall()
 close(conn, cursor)
 return result
def insert(sql,args):
 """
 创建数据
 :param sql: 含有占位符的SQL
 :return:
 """
 conn, cursor = connect()
 # 执行SQL,并返回收影响行数
 effect_row = cursor.execute(sql,args)
 conn.commit()
 close(conn, cursor)
def delete(sql,args):
 """
 创建数据
 :param sql: 含有占位符的SQL
 :return:
 """
 conn, cursor = connect()
 # 执行SQL,并返回收影响行数
 effect_row = cursor.execute(sql,args)
 conn.commit()
 close(conn, cursor)
 return effect_row
def update(sql,args):
 conn, cursor = connect()
 # 执行SQL,并返回收影响行数
 effect_row = cursor.execute(sql, args)
 conn.commit()
 close(conn, cursor)
 return effect_row
登入後複製
###PS: 可以利用靜態方法封裝到一個類別中,方便使用###

以上是如何用Python操作MySQL的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:yisu.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!