Python如何實(shí)現(xiàn)MySQL客戶端操作庫

這篇文章主要介紹了Python如何實(shí)現(xiàn)MySQL客戶端操作庫,具有一定借鑒價(jià)值,需要的朋友可以參考下。希望大家閱讀完這篇文章后大有收獲。下面讓小編帶著大家一起了解一下。

創(chuàng)新互聯(lián)成立于2013年,是專業(yè)互聯(lián)網(wǎng)技術(shù)服務(wù)公司,擁有項(xiàng)目網(wǎng)站建設(shè)、做網(wǎng)站網(wǎng)站策劃,項(xiàng)目實(shí)施與項(xiàng)目整合能力。我們以讓每一個(gè)夢想脫穎而出為使命,1280元新余做網(wǎng)站,已為上家服務(wù),為新余各地企業(yè)和個(gè)人服務(wù),聯(lián)系電話:13518219792

PyMySQL 是一個(gè)純 Python 實(shí)現(xiàn)的 MySQL 客戶端操作庫,支持事務(wù)、存儲(chǔ)過程、批量執(zhí)行等。PyMySQL 遵循 Python 數(shù)據(jù)庫 API v2.0 規(guī)范,并包含了 pure-Python MySQL 客戶端庫。

安裝

pip install PyMySQL

創(chuàng)建數(shù)據(jù)庫連接

import pymysql

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

參數(shù)列表:

參數(shù)描述
host數(shù)據(jù)庫服務(wù)器地址,默認(rèn) localhost
user用戶名,默認(rèn)為當(dāng)前程序運(yùn)行用戶
password登錄密碼,默認(rèn)為空字符串
database默認(rèn)操作的數(shù)據(jù)庫
port數(shù)據(jù)庫端口,默認(rèn)為 3306
bind_address當(dāng)客戶端有多個(gè)網(wǎng)絡(luò)接口時(shí),指定連接到主機(jī)的接口。參數(shù)可以是主機(jī)名或IP地址。
unix_socketunix 套接字地址,區(qū)別于 host 連接
read_timeout讀取數(shù)據(jù)超時(shí)時(shí)間,單位秒,默認(rèn)無限制
write_timeout寫入數(shù)據(jù)超時(shí)時(shí)間,單位秒,默認(rèn)無限制
charset數(shù)據(jù)庫編碼
sql_mode指定默認(rèn)的 SQL_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.
use_unicodeWhether 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設(shè)置默認(rèn)的游標(biāo)類型
init_command當(dāng)連接建立完成之后執(zhí)行的初始化 SQL 語句
connect_timeout連接超時(shí)時(shí)間,默認(rèn) 10,最小 1,最大 31536000
sslA 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.
compressNot supported
named_pipeNot supported
autocommit是否自動(dòng)提交,默認(rèn)不自動(dòng)提交,參數(shù)值為 None 表示以服務(wù)器為準(zhǔn)
local_infileBoolean to enable the use of LOAD DATA LOCAL command. (default: False)
max_allowed_packet發(fā)送給服務(wù)器的最大數(shù)據(jù)量,默認(rèn)為 16MB
defer_connect是否惰性連接,默認(rèn)為立即連接
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 (if no authenticate method) for returning a string from the user. (experimental)
server_public_keySHA256 authenticaiton plugin public key value. (default: None)
db參數(shù) database 的別名
passwd參數(shù) password 的別名
binary_prefixAdd _binary prefix on bytes and bytearray. (default: False)

執(zhí)行 SQL

  • cursor.execute(sql, args) 執(zhí)行單條 SQL

    # 獲取游標(biāo)
    cursor = connection.cursor()
    
    # 創(chuàng)建數(shù)據(jù)表
    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
    ''')
    
    # 插入數(shù)據(jù)(元組或列表)
    effect_row = cursor.execute('INSERT INTO `users` (`name`, `age`) VALUES (%s, %s)', ('mary', 18))
    
    # 插入數(shù)據(jù)(字典)
    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) 批量執(zhí)行 SQL

    # 獲取游標(biāo)
    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 等修改數(shù)據(jù)的語句需手動(dòng)執(zhí)行connection.commit()完成對(duì)數(shù)據(jù)修改的提交。

獲取自增 ID

cursor.lastrowid

查詢數(shù)據(jù)

# 執(zhí)行查詢 SQL
cursor.execute('SELECT * FROM `users`')

# 獲取單條數(shù)據(jù)
cursor.fetchone()

# 獲取前N條數(shù)據(jù)
cursor.fetchmany(3)

# 獲取所有數(shù)據(jù)
cursor.fetchall()

游標(biāo)控制

所有的數(shù)據(jù)查詢操作均基于游標(biāo),我們可以通過cursor.scroll(num, mode)控制游標(biāo)的位置。

cursor.scroll(1, mode='relative') # 相對(duì)當(dāng)前位置移動(dòng)
cursor.scroll(2, mode='absolute') # 相對(duì)絕對(duì)位置移動(dòng)

設(shè)置游標(biāo)類型

查詢時(shí),默認(rèn)返回的數(shù)據(jù)類型為元組,可以自定義設(shè)置返回類型。支持5種游標(biāo)類型:

  • Cursor: 默認(rèn),元組類型

  • DictCursor: 字典類型

  • DictCursorMixin: 支持自定義的游標(biāo)類型,需先自定義才可使用

  • SSCursor: 無緩沖元組類型

  • SSDictCursor: 無緩沖字典類型

無緩沖游標(biāo)類型,適用于數(shù)據(jù)量很大,一次性返回太慢,或者服務(wù)端帶寬較小時(shí)。源碼注釋:

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.

創(chuàng)建連接時(shí),通過 cursorclass 參數(shù)指定類型:

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

也可以在創(chuàng)建游標(biāo)時(shí)指定類型:

cursor = connection.cursor(cursor=pymysql.cursors.DictCursor)

事務(wù)處理

  • 開啟事務(wù)

connection.begin()

  • 提交修改

connection.commit()

  • 回滾事務(wù)

connection.rollback()

防 SQL 注入

  • 轉(zhuǎn)義特殊字符
    connection.escape_string(str)

  • 參數(shù)化語句
    支持傳入?yún)?shù)進(jìn)行自動(dòng)轉(zhuǎn)義、格式化 SQL 語句,以避免 SQL 注入等安全問題。

# 插入數(shù)據(jù)(元組或列表)
effect_row = cursor.execute('INSERT INTO `users` (`name`, `age`) VALUES (%s, %s)', ('mary', 18))

# 插入數(shù)據(jù)(字典)
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),
    ])

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享Python如何實(shí)現(xiàn)MySQL客戶端操作庫內(nèi)容對(duì)大家有幫助,同時(shí)也希望大家多多支持創(chuàng)新互聯(lián),關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,遇到問題就找創(chuàng)新互聯(lián),詳細(xì)的解決方法等著你來學(xué)習(xí)!

當(dāng)前題目:Python如何實(shí)現(xiàn)MySQL客戶端操作庫
URL地址:http://muchs.cn/article10/gjsigo.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供服務(wù)器托管、外貿(mào)網(wǎng)站建設(shè)、網(wǎng)站排名、做網(wǎng)站、企業(yè)網(wǎng)站制作標(biāo)簽優(yōu)化

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)頁設(shè)計(jì)公司