天天看點

技術幹貨|Python mysqlclient 庫常見用法

作者:運維木子李

#頭号有新人#

mysqlclient是Python的一個MySQL資料庫驅動程式,它是Python DB API v2.0的實作之一。

技術幹貨|Python mysqlclient 庫常見用法

它提供了一組函數和方法來連接配接MySQL資料庫,并執行各種資料庫操作。

連接配接到MySQL資料庫:

import MySQLdb

conn = MySQLdb.connect(host='localhost', user='user', passwd='password', db='database')           

建立遊标對象:

cursor = conn.cursor()           

執行SQL查詢:

cursor.execute('SELECT * FROM table')           

擷取查詢結果:

result = cursor.fetchall()           

插入資料:

cursor.execute('INSERT INTO table (column1, column2) VALUES (%s, %s)', ('value1', 'value2'))           

送出事務:

conn.commit()           

復原事務:

conn.rollback()           

擷取受影響的行數:

affected_rows = cursor.rowcount           

擷取插入的自增ID:

last_insert_id = cursor.lastrowid           

更新資料:

cursor.execute('UPDATE table SET column1 = %s WHERE column2 = %s', ('new_value', 'condition'))           

删除資料:

cursor.execute('DELETE FROM table WHERE column = %s', ('value',))           

批量插入資料:

data = [('value1', 'value2'), ('value3', 'value4')]
cursor.executemany('INSERT INTO table (column1, column2) VALUES (%s, %s)', data)           

擷取字段資訊:

fields = cursor.description           

擷取表的主鍵:

cursor.execute('SHOW KEYS FROM table WHERE Key_name = "PRIMARY"')
primary_key = cursor.fetchone()[0]           

擷取表的索引:

cursor.execute('SHOW INDEX FROM table')indexes = cursor.fetchall()           

擷取表的建立語句:

cursor.execute('SHOW INDEX FROM table')
indexes = cursor.fetchall()           

執行存儲過程:

cursor.callproc('procedure_name', args)           

擷取存儲過程的輸出參數:

output_param = cursor.fetchone()           

執行事務:

try:
    cursor.execute('START TRANSACTION')
    # 執行其他SQL語句
    cursor.execute('COMMIT')
except:
    cursor.execute('ROLLBACK')           

設定字元集:

conn.set_charset('utf8')           

設定自動送出模式:

conn.autocommit(True)           

設定逾時時間:

conn.set_timeout(10)           

設定查詢緩存:

conn.query('SET SESSION query_cache_type = ON')           

設定連接配接池大小:

conn.set_max_connections(10)           

關閉遊标對象:

cursor.close()           

關閉資料庫連接配接:

conn.close()           

使用上下文管理器連接配接資料庫:

import MySQLdb

with MySQLdb.connect(host='localhost', user='user', passwd='password', db='database') as conn:
    cursor = conn.cursor()
    # 執行資料庫操作           

使用上下文管理器執行事務:

import MySQLdb

with MySQLdb.connect(host='localhost', user='user', passwd='password', db='database') as conn:
    with conn.cursor() as cursor:
        try:
            cursor.execute('START TRANSACTION')
            # 執行其他SQL語句
            cursor.execute('COMMIT')
        except:
            cursor.execute('ROLLBACK')           

設定連接配接屬性:

conn.set_session(sql_mode='ANSI')           

擷取連接配接屬性:

sql_mode = conn.get_session().get('sql_mode')           

設定連接配接逾時時間:

conn.set_connect_timeout(10)           

擷取連接配接逾時時間:

connect_timeout = conn.get_connect_timeout()           

設定查詢逾時時間:

conn.set_query_timeout(10)           

擷取查詢逾時時間:

query_timeout = conn.get_query_timeout()           

設定讀取逾時時間:

conn.set_read_timeout(10)           

擷取讀取逾時時間:

read_timeout = conn.get_read_timeout()           

設定寫入逾時時間:

conn.set_write_timeout(10)           

擷取寫入逾時時間:

write_timeout = conn.get_write_timeout()           

打開SSL連接配接:

conn.ssl_set(ca='path/to/ca.pem', cert='path/to/cert.pem', key='path/to/key.pem')           

擷取SSL連接配接狀态:

ssl_enabled = conn.ssl_in_use()Python           

執行帶參數的SQL查詢:

cursor.execute('SELECT * FROM table WHERE column = %s', ('value',))           

執行帶參數的SQL查詢,并擷取結果:

cursor.execute('SELECT * FROM table WHERE column = %s', ('value',))
result = cursor.fetchall()           

擷取查詢結果的字段名:

fields = [desc[0] for desc in cursor.description]           

擷取查詢結果的字段類型:

field_types = [desc[1] for desc in cursor.description]           

使用連接配接池連接配接資料庫:

import MySQLdb
from DBUtils.PersistentDB import PersistentDB

db_pool = PersistentDB(MySQLdb, host='localhost', user='user', passwd='password', db='database')
conn = db_pool.connection()
cursor = conn.cursor()
# 執行資料庫操作           

這些示例涵蓋了mysqlclient子產品的一系列功能,包括連接配接資料庫、執行SQL語句、事務處理、批量插入、擷取表資訊等。希望對你有所幫助!

mysql相關技術幹貨:

mysql8安全基線及安全優化

mysql8.0安裝、部署及優化

技術幹貨|Python MySQL驅動子產品mysql-connector-python常見用法

Shell腳本來實作MySQL服務的定時健康性檢查

shell腳本實作mysql資料庫檔案和日志備份

技術幹貨|MySQL 8索引優化、查詢優化、表設計優化和配置優化

Ansible實作生産環境一鍵式Linux+Nginx+MySQL+Tomcat企業級架構

python其他技術幹貨

Python-一些基本概念

Python基本文法規則

python open函數的解釋以及示例及python檔案指針操作

python Django渲染原理及應用

Python argparse子產品作用及應用

python繼承與多态-新式類和古典類差別

python3 多程序應用場景及示例

python 一些操作時間複雜度及效率

python繼承與多态-新式類和古典類差別

Python-進制表示和互相轉換

Python中導入子產品或對象的方式

Python-線性表概念和分類

Python-清單常見初始化方式

python繼承與多态-執行個體屬性的通路規則

python多程序并行排序的應用示例

python多程序矩陣計算的應用示例

python子產品搜尋順序和子產品緩存

python目錄、檔案删除方法及詳細示例

Python常見的可調用對象類型示例

python多程序并行求和應用示例

python3 多線程應用場景及示例

python3 path子產品相關應用舉例說明

python繼承與多态-新式類和古典類差別

python __str__、__repr__和__bytes__功能及應用示例