Python3鏈接Mysql數據庫

今天來介紹python鏈接MySQL的操作流程。

pymysql 的安裝

這裏推薦直接 pip方法安裝, 方便快捷,省時省事!

 pip instal  pymysql

pymysql 的使用

鏈接數據庫操作,無非就是以下這幾個步驟;
1.創建數據庫鏈接;
2.進行sql語句操作;
3.關閉數據庫鏈接;

所以,我們接下來,就看看,如何連接數據庫,如何進行操作。

創建數據庫鏈接

import pymysql

#鏈接數據庫
connection = pymysql.connect(
    host = "localhost",   #填寫數據庫的主機IP地址
    user = 'root',        #數據庫用戶名
    password = '123456',  #數據庫密碼
    port = '3306',        #數據庫端口號
    database = 'test',    #數據庫的名稱
)

sql語句操作

我們如何進行sql語句操作呢?
cursor方法:

cursor提供了三種方法,分別是 fetchone,fetchmany,fetchall。
①fetchone() :用於查詢單條數據,返回元組,沒有返回None;
②fetchmany(size) : 接受size行返回結果。如果size大於返回的結果行數量,怎返回cursor.arraysize條數據;
③fetchall():用於查詢全部數據。

commit() 提交事務

connection.commit():將修改的數據提交到數據庫;

fetchall():查詢全部語句

#創建sql語句
sql = "select * from base_role   where role_name = '管理員'"
#執行sql語句
try:
    cursor.execute(sql)
    results = cursor.fetchall()  #全部查詢
    for i in results:
        role_id  = i['id']
        print(role_id)
except Exception as e:
    print("Unable to fetch  data!", format(e))

fetchone():查詢單條語句

#創建sql語句並執行
sql = "select * from base_role where role_name = '系統管理員'"
cursor.execute(sql)

#查詢單條數據
result = cursor.fetchone()
print(result)

fetchmany():查詢多條語句

#創建sql語句並執行
sql = "select * from base_role"
cursor.execute(sql)

#查詢多條數據
results = cursor.fetchmany(5) # 獲取5條數據
print(type(results))
for res in results:
    print(res)

關閉數據庫鏈接

# 創建sql語句操作_更新
updata = "updata base_role  set role_name = '系統管理員'  where role_code = 3 "
cursor.execute(updata)

#查詢單條數據
sql = "select * from base_role where role_name = '系統管理員'"
cursor.execute(sql)
#執行sql語句
result = cursor.fetchone()
print(result)

#提交sql語句
connection.commit()
#關閉數據庫鏈接
connection.close()


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