1. 程式人生 > 實用技巧 >python自動化之pymysql庫連線mysql資料庫封裝成類

python自動化之pymysql庫連線mysql資料庫封裝成類

import pymysql

if __name__ == '__main__':

host = "被訪問資料庫的ip地址或者域名"
port = 埠號
user = "連線資料庫的使用者名稱"
password = "連線資料庫的密碼"
sql = "要查詢的SQL語句 "

# 連線一個給定的資料庫,autocommit 預設是False,改成True後會自動幫你提交sql命令
mysql = pymysql.connect(host=host,user= user,password=password,port=port,charset="utf8",autocommit=True)

# 建立遊標用來執行資料庫操作
cursor = mysql.cursor()

# 執行sql命令
cursor.execute(sql)

#提交sql命令
mysql.commit()

# fetchone() :返回單個的元組,也就是一條記錄(row),如果沒有結果 則返回 None
# fetchall() : 返回多個列表套元組,即返回多個記錄(rows),如果沒有結果 則返回 ()
# 獲取前n行資料 data = cursor.fetchmany(3) 獲取前三行資料,元組包含元組
# 需要註明:在MySQL中是NULL,而在Python中則是None

data = cursor.fetchone()
print(data)

# 關閉遊標
cursor.close()

# 關閉資料庫連線
mysql.close()


以下是將pymysql要用到的功能進行了封裝
class  MysqlHandler:
#建立資料庫連線,新建一個查詢頁面
def __init__(self):
# port要轉為int,這裡的各項值是利用的封裝好的配置檔案configparser庫進行的傳入section,option進行的讀取
self.mysql = pymysql.connect(host= config.handles.get_value("mysql", "connection"),
user = config.handles.get_value("mysql", "user"),
password=config.handles.get_value("mysql", "password"),
port= int(config.handles.get_value("mysql", "port")), charset="utf8", autocommit=True)
self.cursor = self.mysql.cursor(pymysql.cursors.DictCursor) # fetchone 是字典 fetchalllistdict

#獲取查詢結果,結果是dict,上面建立遊標指定了是dict
def query_one(self,sql):
self.cursor.execute(sql)
data = self.cursor.fetchone()
return data

#關閉查詢頁面,關閉連線
def close(self):
self.cursor.close()
self.mysql.close()