Python 深入淺出 - PyMySQL 操作 MySQL 數據庫

不知不覺 2017 就已經結束了,2018 元旦快樂。

回顧 2017 ,真是碌碌無爲;希望 2018 勿忘初心,好好努力,早日實現新年願望:

  • 提升自身技術,堅持把 Java 後端技術學好;
  • 輕鬆購買 MBP,而不會覺得價格貴;
  • 努力賺錢,買車;
  • 妹子;

祝自己好運~~~~

Python 的數據庫接口標準時 Python DB-API,大多數 Python 數據庫接口都遵循這個標準。爲了兼容 Python 3,本文使用 PyMySQL 庫進行操作 MySQL 數據庫。

Python DB-API 使用流程

  1. 引入 API 模塊
  2. 獲取與數據庫的連接
  3. 執行 SQL 語句和存儲過程。
  4. 關閉數據庫連接

PyMySQL 介紹

PyMySQL 是 Python 連接 MySQL 數據庫服務器的接口,他實現了 Python 數據庫 API v2.0,幷包含了一個純 Python 的 MySQL 客戶端庫。

PyMySQL參考文檔:http://pymysql.readthedocs.io

安裝 PyMySQL

C:\Users\Administrator> pip install PyMySQL

install-pymysql

數據庫簡單操作

連接數據庫之前,先使用 MySQL 客戶端 SQLyog 手動創建好數據庫和表:

# 創建數據庫
CREATE DATABASE db_study

# 創建表
CREATE TABLE tb_student
(
    id INT NOT NULL AUTO_INCREMENT,
    `name` CHAR(20) NOT NULL,
    gender CHAR(1) DEFAULT NULL,
    age INT DEFAULT NULL,
    score INT DEFAULT NULL,
    PRIMARY KEY(id)
)ENGINE = INNODB DEFAULT CHARSET = utf8

此例查詢數據庫版本號:

# 0. import db
import pymysql
# 1. open database connection
db = pymysql.connect('localhost','root','root','db_study')

# 2. prepare a cursor object using cursor() method
cursor  = db.cursor()

# 3. execute SQL query using execute() method
cursor.execute('SELECT VERSION()')

# 4. fetch a single row using fetchone() method
version = cursor.fetchone()

print('database version : %s' % version)

# 5. disconnect from db server
db.close()

輸出結果:

database version : 5.5.36

insert 操作

# 0. import db
import pymysql
# 1. open database connection
db = pymysql.connect('localhost','root','root','db_study')

# 2. prepare a cursor object using cursor() method
cursor  = db.cursor()

# 3. execute SQL command
sql = "insert into tb_student(name,gender,age,score) values('mike','F',21,90 )"
print('sql = %s' % sql)
try:
    cursor.execute(sql)
    db.commit()
except:
    db.rollback()

print('insert sucess')

# 4. disconnect from db server
db.close()

輸出結果:

sql = insert into tb_student(name,gender,age,score) values('mike','F',21,90 )
insert sucess

select 操作

遊標 Cursor 對象的屬性和方法 描述
fetchone() 它用來獲取使用遊標對象來查詢表時,返回的結果集對象中的下一行數據
fetchall() 它用來獲取使用遊標對象來查詢表時,返回的結果集對象中的所有行數據
rowcount 只讀屬性,返回 execute() 方法影響的行數
# 0. import db
import pymysql
# 1. open database connection
db = pymysql.connect('localhost','root','root','db_study')

# 2. prepare a cursor object using cursor() method
cursor  = db.cursor()

# 3. execute SQL command
sql_select = 'SELECT * FROM tb_student'
print(sql_select)
try:
    cursor.execute(sql_select)
    res  = cursor.fetchone()
    # cursor.scroll(0,'absolute')  # scroll 移動遊標的位置,mode = 'relative' 或 'absolute'
    print('fetchone ===> id = %s,name = %s,gender = %s,age = %d,score = %d ' % (res[0],res[1],res[2],res[3],res[4]))
    print('rowcount = %d' % cursor.rowcount)
    result = cursor.fetchall()
    for row in result:
        id = row[0]
        name = row[1]
        gender = row[2]
        age = row[3]
        score = row[4]
        print('id = %s,name = %s,gender = %s,age = %d,score = %d' % (id,name,gender,age,score))
except:
    import traceback
    traceback.print_exc()
    print('execute error')

# 4. disconnect from db server
db.close()

輸出結果:

SELECT * FROM tb_student
fetchone ===> id = 1,name = mike,gender = F,age = 21,score = 90 
rowcount = 2
id = 5,name = jane,gender = M,age = 24,score = 95

data-row

數據庫表中是有兩條數據,但是上面代碼中先使用了 cursor.fetchone() 獲取一個數據,再使用 cursor.fetchall() 獲取所有行數據,導致獲取所有行時,只獲取了剩下行的數據,這是因爲在 fetchone() 之後,遊標已經處於第 1 行的位置上,而不是第 0 行,要想 fetchall() 獲取所有行數據,則需要將遊標重新移動到第 0 行位置上,即使用 cursor.scroll(0,’absolute’) ,放開上面代碼註釋即可。

輸出結果:

SELECT * FROM tb_student
fetchone ===> id = 1,name = mike,gender = F,age = 21,score = 90 
rowcount = 2
id = 1,name = mike,gender = F,age = 21,score = 90
id = 5,name = jane,gender = M,age = 24,score = 95

update 操作

將 age = 24 的記錄的 score 增加 5 分

# 0. import db
import pymysql
# 1. open database connection
db = pymysql.connect('localhost','root','root','db_study')

# 2. prepare a cursor object using cursor() method
cursor  = db.cursor()
# 3. execute SQL command
sql_update = 'UPDATE tb_student SET score = score + 5 WHERE age = 24 '
print('sql_update = %s' % sql_update)
try:
    cursor.execute(sql_update)
    db.commit()
    print('update success')
except:
    db.rollback()
    print('update error')
# 4. disconnect from db server
db.close()

操作後的結果:

update-result

delete 操作

# 0. import db
import pymysql

# 1. open database connection
db = pymysql.connect('localhost', 'root', 'root', 'db_study')

# 2. prepare a cursor object using cursor() method
cursor = db.cursor()

# 3. execute SQL command
# delete row
sql_delete = 'DELETE FROM tb_student WHERE age < 24'
print('sql_delete = %s' % sql_delete)
try:
    cursor.execute(sql_delete)
    db.commit()
    print('delete success')
except:
    db.rollback()
    print('delete error')
print('delete rowcount = %d' % cursor.rowcount)

# query all row
sql_select = 'SELECT * FROM tb_student'
print('sql_select = %s' % sql_select)
try:
    cursor.execute(sql_select)
    print('select rowcount = %d' % cursor.rowcount)
    result = cursor.fetchall()
    for row in result:
        id = row[0]
        name = row[1]
        gender = row[2]
        age = row[3]
        score = row[4]
        print('id = %s,name = %s,gender = %s,age = %d,score = %d' % (id, name, gender, age, score))
except:
    import traceback
    traceback.print_exc()
    print('execute error')

# 4. disconnect from db server
db.close()

輸出結果:

sql_delete = DELETE FROM tb_student WHERE age < 24
delete success
delete rowcount = 1
sql_select = SELECT * FROM tb_student
select rowcount = 1
id = 5,name = jane,gender = M,age = 24,score = 100

執行事務

事務是確保數據一致性的一種機制,事務具有四大屬性:

  • 原子性: 指事務包含的所有操作要麼全部成功,要麼全部失敗回滾。
  • 一致性: 事務應確保數據庫的狀態從一個一致狀態轉變成另一個一致狀態,一致狀態的含義是數據庫中的數據應滿足完整性約束。
  • 隔離性 : 多個事務併發執行時,一個事務的執行不應影響其他事務的執行。
  • 持久性: 一個事務一旦提交,它對數據庫的修改應該永久保存在數據庫中。
操作 描述
db.commit() 提交事務
db.rollback() 回滾事務

移動遊標

移動遊標操作 描述
cursor.scroll(1,mode = ‘relative’) 相對於當前位置移動
cursor.scroll(2,mode = ‘absolute’) 相對於絕對位置移動

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