pymysql 操作 mysql 樣例

前言:

python 中常用的連接 mysql 的包有兩個 MySQLdb 和 pymysql,用法大致相同,這裏只介紹 pymysql 用法。

1.安裝
pip install pymysql
2.獲取連接
import pymysql
 
 # 連接database
conn = pymysql.connect(
    host=“你的數據庫地址”,
    user=“用戶名”,password=“密碼”,
    database=“數據庫名”,
    charset=“utf8”)
    
# 得到一個可以執行SQL語句的光標對象
cursor = conn.cursor()  # 默認執行完畢返回的結果集默認以元組顯示
# 也可以指定返回類型爲字典,如下
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
3.數據操作

增刪改查中,增刪改在執行sql語句以後一定要提交,查詢不需要提交,如下:

# 查詢
sql = "select * from table where id='999'"

# count 是滿足查詢條件的信息數量
count = cursor.execute(sql) 

# 獲取查詢數據有三種方式,返回結果是按照查詢順序排列的元祖
info = cursor.fetchall()   # 獲取全部數據
info = cursor.fetchone()  # 獲取第一條數據
info = cursor.fetchmany(num)  # 獲取前 num 條數據

插入數據單獨說一下,主要是有單條數據插入,和多條數據插入的不同

# 插入一條數據
sql = "insert into db(id,name,age) values('1','qingquan','25')"
result = cursor.execute(sql)
# 一定要有下面這句提交語句,不然插入數據不生效
conn.commit()

# 插入多條語句
sql  = "insert into db(id,name,age) values('%s','%s','%s')"
# data 是 list,,每個成員是 tuple
data = {
	('1','quan','25'),
	('2','qing','25'),
}
result = cursor.executemany(sql , data)
conn.commit()

刪除和修改數據和插入一條數據除了 sql 語句不一樣,其他都是同樣的操作

4.其他操作notes

1.獲取插入數據最後一條的自增 id

# 在有自增 id 的表中,可以在插入數據提交以後,使用下面函數獲取最後一條數據的自增 id
last_id = cursor.lastrowid

2.防 sql 注入攻擊

# 大部分時候我們使用下面方式構建 sql 語句
sql = "select * from test_db where id = '%s'" % ('1',)

# pymysql 有一個 sql 語句防注入的構建模式
sql = cursor.mogrify( "select * from test_db where id = '%s'", ('1',))

3.事務回滾
事務由作爲一個單獨單元的一個或多個SQL語句組成,如果其中一個語句不能完成,整個單元就會回滾(撤銷),所有影響到的數據將返回到事務開始以前的狀態。因而,只有事務中的所有語句都成功地執行才能說這個事務被成功地執行。

conn.rollback()

3.爲了防止數據操作過程中報錯,可以使用 try…except…finally的結構

5.關閉數據庫連接

如果數據庫操作完成一定要記得把連接關掉,這樣可以減輕 mysql 的連接負載

# 先關遊標
cursor.close()

# 再關連接
conn.close()
6.完整例子
def mysql_operation(name, age):
    conn = pymysql.connect(host='', port=3306, user='', password='', db='')
    cursor = conn.cursor()

    insert_sql = "insert into test_db(name,age) values('%s','%s')" % (name, age)
    try:
        select_sql = cursor.mogrify("select * from test_db where name = '%s'", (name,))
        count = cursor.execute(select_sql ) 
        if response >= 1:
            print(u'已存在...')
        else:
            try:
                cursor.execute(insert_sql)
                conn.commit()
                print(u'更新成功...')
            except Exception as e:
                print(u'更新錯誤...', e)
                conn.rollback()
    except Exception as e:
        print(u'查詢錯誤...', e)
        conn.rollback()
    finally:
        cursor.close()
        conn.close()
7.參考資料

pymysql操作mysql詳解
對mysql事務提交、回滾的錯誤理解

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章