目錄
安裝
建立資料庫連線
执行 SQL
获取自增 ID
查询数据
游标控制
设置游标类型
事务处理
防 SQL 注入
参考资料
首頁 資料庫 mysql教程 分享一個純 Python 實作的 MySQL 用戶端操作庫

分享一個純 Python 實作的 MySQL 用戶端操作庫

Jul 25, 2018 pm 04:33 PM
mysql pymysql python

PyMySQL 是一個純 Python 實作的 MySQL 用戶端操作函式庫,支援事務、預存程序、批次執行等。 PyMySQL 遵循 Python 資料庫 API v2.0 規範,並包含了 pure-Python MySQL 用戶端程式庫。

安裝

pip install PyMySQL
登入後複製

建立資料庫連線

import pymysql

connection = pymysql.connect(host='localhost',
                             port=3306,
                             user='root',
                             password='root',
                             db='demo',
                             charset='utf8')
登入後複製

參數清單:

##參數hostuserpassworddatabaseportbind_addressunix_socketread_timeoutwrite_timeoutcharsetsql_mode##read_default_fileSpecifies my.cnf file to read these parameters from under the [client] section.convConversion dictionary to use instead of the default one. This is used to provide custom marshalling and unmarshaling of types.Whether or not to default to unicode strings. This option defaults to true for Py3k.##client_flagCustom flags to send to MySQL. Find potential values in constants.CLIENT.cursorclass設定預設的遊標類型init_command當連線建立完成之後執行的初始化SQL 語句connect_timeout連線逾時時間,預設10,最小1,最大31536000sslA dict of arguments similar to mysql_ssl_set()'s parameters. For now the capath and cipher arguments are not supported.#read_default_groupGroup to read from in the configuration file.compress Not supportednamed_pipeNot supported參數database 的別名參數password 的別名#Add _binary prefix on bytes and bytearray. (default: False)
##描述
資料庫伺服器位址,預設localhost
使用者名,預設為目前程式運行使用者
登入密碼,預設為空字串
預設操作的資料庫
資料庫端口,預設為3306
#當客戶端有多個網路介面時,指定連接到主機的介面。參數可以是主機名稱或IP位址。
unix 套接字位址,區別於host 連線
#讀取資料逾時時間,單位秒,預設無限制
寫入資料逾時時間,單位秒,預設無限制
資料庫編碼
指定預設的SQL_MODE
##use_unicode
##autocommit是否自動提交,預設不自動提交,參數值為None 表示以伺服器為準
local_infileBoolean to enable the use of LOAD DATA LOCAL command. (default: False )
max_allowed_pa​​cket傳送給伺服器的最大資料量,預設為16MB
defer_connect是否惰性連接,預設為立即連接
auth_plugin_mapA dict of plugin names to a class that processes that plugin. The class will take the Connection object as the argument to the constructor. The class needs an authenticate method taking an authentication packet as an argument.  For the dialog plugin, a prompt(echo, prompt) method can be used (iff ental moper method ental for returning returning . )
server_public_keySHA256 authenticaiton plugin public key value. (default: None)
db#db
db
passwd
binary_prefix
#######

执行 SQL

  • cursor.execute(sql, args) 执行单条 SQL

    # 获取游标
    cursor = connection.cursor()
    
    # 创建数据表
    effect_row = cursor.execute('''
    CREATE TABLE `users` (
      `name` varchar(32) NOT NULL,
      `age` int(10) unsigned NOT NULL DEFAULT '0',
      PRIMARY KEY (`name`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8
    ''')
    
    # 插入数据(元组或列表)
    effect_row = cursor.execute('INSERT INTO `users` (`name`, `age`) VALUES (%s, %s)', ('mary', 18))
    
    # 插入数据(字典)
    info = {'name': 'fake', 'age': 15}
    effect_row = cursor.execute('INSERT INTO `users` (`name`, `age`) VALUES (%(name)s, %(age)s)', info)
    
    connection.commit()
    登入後複製
  • executemany(sql, args) 批量执行 SQL

    # 获取游标
    cursor = connection.cursor()
    
    # 批量插入
    effect_row = cursor.executemany(
        'INSERT INTO `users` (`name`, `age`) VALUES (%s, %s) ON DUPLICATE KEY UPDATE age=VALUES(age)', [
            ('hello', 13),
            ('fake', 28),
        ])
    
    connection.commit()
    登入後複製

注意:INSERT、UPDATE、DELETE 等修改数据的语句需手动执行connection.commit()完成对数据修改的提交。

获取自增 ID

cursor.lastrowid
登入後複製

查询数据

# 执行查询 SQL
cursor.execute('SELECT * FROM `users`')

# 获取单条数据
cursor.fetchone()

# 获取前N条数据
cursor.fetchmany(3)

# 获取所有数据
cursor.fetchall()
登入後複製

游标控制

所有的数据查询操作均基于游标,我们可以通过cursor.scroll(num, mode)控制游标的位置。

cursor.scroll(1, mode='relative') # 相对当前位置移动
cursor.scroll(2, mode='absolute') # 相对绝对位置移动
登入後複製

设置游标类型

查询时,默认返回的数据类型为元组,可以自定义设置返回类型。支持5种游标类型:

  • Cursor: 默认,元组类型

  • DictCursor: 字典类型

  • DictCursorMixin: 支持自定义的游标类型,需先自定义才可使用

  • SSCursor: 无缓冲元组类型

  • SSDictCursor: 无缓冲字典类型

无缓冲游标类型,适用于数据量很大,一次性返回太慢,或者服务端带宽较小时。源码注释:

Unbuffered Cursor, mainly useful for queries that return a lot of data, or for connections to remote servers over a slow network.

Instead of copying every row of data into a buffer, this will fetch rows as needed. The upside of this is the client uses much less memory, and rows are returned much faster when traveling over a slow network
or if the result set is very big.

There are limitations, though. The MySQL protocol doesn't support returning the total number of rows, so the only way to tell how many rows there are is to iterate over every row returned. Also, it currently isn't possible to scroll backwards, as only the current row is held in memory.

创建连接时,通过 cursorclass 参数指定类型:

connection = pymysql.connect(host='localhost',
                             user='root',
                             password='root',
                             db='demo',
                             charset='utf8',
                             cursorclass=pymysql.cursors.DictCursor)
登入後複製

也可以在创建游标时指定类型:

cursor = connection.cursor(cursor=pymysql.cursors.DictCursor)
登入後複製

事务处理

  • 开启事务

connection.begin()

  • 提交修改

connection.commit()

  • 回滚事务

connection.rollback()

防 SQL 注入

  • 转义特殊字符
    connection.escape_string(str)

  • 参数化语句
    支持传入参数进行自动转义、格式化 SQL 语句,以避免 SQL 注入等安全问题。

# 插入数据(元组或列表)
effect_row = cursor.execute('INSERT INTO `users` (`name`, `age`) VALUES (%s, %s)', ('mary', 18))

# 插入数据(字典)
info = {'name': 'fake', 'age': 15}
effect_row = cursor.execute('INSERT INTO `users` (`name`, `age`) VALUES (%(name)s, %(age)s)', info)

# 批量插入
effect_row = cursor.executemany(
    'INSERT INTO `users` (`name`, `age`) VALUES (%s, %s) ON DUPLICATE KEY UPDATE age=VALUES(age)', [
        ('hello', 13),
        ('fake', 28),
    ])
登入後複製

参考资料

  • Python中操作mysql的pymysql模块详解

  • Python之pymysql的使用

相关推荐:

python实现telnet客户端的方法

MemCached的PHP客户端操作类二

数据库mysql视频教程

以上是分享一個純 Python 實作的 MySQL 用戶端操作庫的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

<🎜>:泡泡膠模擬器無窮大 - 如何獲取和使用皇家鑰匙
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系統,解釋
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆樹的耳語 - 如何解鎖抓鉤
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1665
14
CakePHP 教程
1424
52
Laravel 教程
1321
25
PHP教程
1269
29
C# 教程
1249
24
MySQL和PhpMyAdmin:核心功能和功能 MySQL和PhpMyAdmin:核心功能和功能 Apr 22, 2025 am 12:12 AM

MySQL和phpMyAdmin是強大的數據庫管理工具。 1)MySQL用於創建數據庫和表、執行DML和SQL查詢。 2)phpMyAdmin提供直觀界面進行數據庫管理、表結構管理、數據操作和用戶權限管理。

Python vs. JavaScript:開發環境和工具 Python vs. JavaScript:開發環境和工具 Apr 26, 2025 am 12:09 AM

Python和JavaScript在開發環境上的選擇都很重要。 1)Python的開發環境包括PyCharm、JupyterNotebook和Anaconda,適合數據科學和快速原型開發。 2)JavaScript的開發環境包括Node.js、VSCode和Webpack,適用於前端和後端開發。根據項目需求選擇合適的工具可以提高開發效率和項目成功率。

在MySQL中解釋外鍵的目的。 在MySQL中解釋外鍵的目的。 Apr 25, 2025 am 12:17 AM

在MySQL中,外鍵的作用是建立表與表之間的關係,確保數據的一致性和完整性。外鍵通過引用完整性檢查和級聯操作維護數據的有效性,使用時需注意性能優化和避免常見錯誤。

Golang vs. Python:利弊 Golang vs. Python:利弊 Apr 21, 2025 am 12:17 AM

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Laravel vs. Python(與框架):比較分析 Laravel vs. Python(與框架):比較分析 Apr 21, 2025 am 12:15 AM

Laravel適合團隊熟悉PHP且需功能豐富的項目,Python框架則視項目需求而定。 1.Laravel提供優雅語法和豐富功能,適合需要快速開發和靈活性的項目。 2.Django適合複雜應用,因其“電池包含”理念。 3.Flask適用於快速原型和小型項目,提供極大靈活性。

Python vs. C:了解關鍵差異 Python vs. C:了解關鍵差異 Apr 21, 2025 am 12:18 AM

Python和C 各有優勢,選擇應基於項目需求。 1)Python適合快速開發和數據處理,因其簡潔語法和動態類型。 2)C 適用於高性能和系統編程,因其靜態類型和手動內存管理。

比較和對比Mysql和Mariadb。 比較和對比Mysql和Mariadb。 Apr 26, 2025 am 12:08 AM

MySQL和MariaDB的主要區別在於性能、功能和許可證:1.MySQL由Oracle開發,MariaDB是其分支。 2.MariaDB在高負載環境中性能可能更好。 3.MariaDB提供了更多的存儲引擎和功能。 4.MySQL採用雙重許可證,MariaDB完全開源。選擇時應考慮現有基礎設施、性能需求、功能需求和許可證成本。

SQL與MySQL:澄清兩者之間的關係 SQL與MySQL:澄清兩者之間的關係 Apr 24, 2025 am 12:02 AM

SQL是一種用於管理關係數據庫的標準語言,而MySQL是一個使用SQL的數據庫管理系統。 SQL定義了與數據庫交互的方式,包括CRUD操作,而MySQL實現了SQL標準並提供了額外的功能,如存儲過程和触發器。

See all articles