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')
參數清單:
##描述 | |
---|---|
資料庫伺服器位址,預設localhost | |
使用者名,預設為目前程式運行使用者 | |
登入密碼,預設為空字串 | |
預設操作的資料庫 | |
資料庫端口,預設為3306 | |
#當客戶端有多個網路介面時,指定連接到主機的介面。參數可以是主機名稱或IP位址。 | |
unix 套接字位址,區別於host 連線 | |
#讀取資料逾時時間,單位秒,預設無限制 | |
寫入資料逾時時間,單位秒,預設無限制 | |
資料庫編碼 | |
指定預設的SQL_MODE | ##read_default_file |
conv | |
##use_unicode | |
##client_flag | Custom flags to send to MySQL. Find potential values in constants.CLIENT. |
cursorclass | 設定預設的遊標類型 |
init_command | 當連線建立完成之後執行的初始化SQL 語句 |
connect_timeout | 連線逾時時間,預設10,最小1,最大31536000 |
ssl | A dict of arguments similar to mysql_ssl_set()'s parameters. For now the capath and cipher arguments are not supported. |
#read_default_group | Group to read from in the configuration file. |
compress | Not supported |
named_pipe | Not supported |
##autocommit | 是否自動提交,預設不自動提交,參數值為None 表示以伺服器為準 |
local_infile | Boolean to enable the use of LOAD DATA LOCAL command. (default: False ) |
max_allowed_packet | 傳送給伺服器的最大資料量,預設為16MB |
defer_connect | 是否惰性連接,預設為立即連接 |
auth_plugin_map | A 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_key | SHA256 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 實作的 MySQL 用戶端操作庫的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本篇文章给大家带来了关于mysql的相关知识,其中主要介绍了关于架构原理的相关内容,MySQL Server架构自顶向下大致可以分网络连接层、服务层、存储引擎层和系统文件层,下面一起来看一下,希望对大家有帮助。

在mysql中,可以利用char()和REPLACE()函数来替换换行符;REPLACE()函数可以用新字符串替换列中的换行符,而换行符可使用“char(13)”来表示,语法为“replace(字段名,char(13),'新字符串') ”。

mysql的msi与zip版本的区别:1、zip包含的安装程序是一种主动安装,而msi包含的是被installer所用的安装文件以提交请求的方式安装;2、zip是一种数据压缩和文档存储的文件格式,msi是微软格式的安装包。

转换方法:1、利用cast函数,语法“select * from 表名 order by cast(字段名 as SIGNED)”;2、利用“select * from 表名 order by CONVERT(字段名,SIGNED)”语句。

本篇文章给大家带来了关于mysql的相关知识,其中主要介绍了关于MySQL复制技术的相关问题,包括了异步复制、半同步复制等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于mysql的相关知识,其中主要介绍了mysql高级篇的一些问题,包括了索引是什么、索引底层实现等等问题,下面一起来看一下,希望对大家有帮助。

在mysql中,可以利用REGEXP运算符判断数据是否是数字类型,语法为“String REGEXP '[^0-9.]'”;该运算符是正则表达式的缩写,若数据字符中含有数字时,返回的结果是true,反之返回的结果是false。

“mysql-connector”是mysql官方提供的驱动器,可以用于连接使用mysql;可利用“pip install mysql-connector”命令进行安装,利用“import mysql.connector”测试是否安装成功。


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

Dreamweaver CS6
視覺化網頁開發工具

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),