分享一個python數(shù)據(jù)庫操作pymysql的簡單封裝
import pymysql
class MyDatabase(object):
def __init__(self, host, port, user, password, database, charset='utf8'):
self.host = host
self.port = port
self.user = user
self.password = password
self.database = database
self.charset = charset
self._conn = None
self._cursor = None
def connect(self):
self._conn = pymysql.connect(
host=self.host,
port=self.port,
user=self.user,
password=self.password,
database=self.database,
charset=self.charset)
self._cursor = self._conn.cursor()
def execute(self, sql, params=None, commit=True):
if not self._cursor:
self.connect()
try:
self._cursor.execute(sql, params)
if commit:
self._conn.commit()
except:
self._conn.rollback()
raise
def query_all(self, sql, params=None):
if not self._cursor:
self.connect()
result = None
try:
self._cursor.execute(sql, params)
result = self._cursor.fetchall()
except:
raise
return result
def query_one(self, sql, params=None):
if not self._cursor:
self.connect()
result = None
try:
self._cursor.execute(sql, params)
result = self._cursor.fetchone()
except:
raise
return result
def close(self):
if self._cursor:
self._cursor.close()
if self._conn:
self._conn.close()
在這個封裝類中筹我,我們使用了Pymysql庫連接MySQL數(shù)據(jù)庫。我們創(chuàng)建了一個MySQL類再登,該類的初始化方法init()接受MySQL連接的參數(shù),包括host、port字旭、user、password崖叫、database和charset遗淳。
實現(xiàn)了以下幾個方法:
connect():連接到MySQL數(shù)據(jù)庫。
execute():執(zhí)行SQL查詢或更新心傀,支持傳入?yún)?shù)屈暗,例如常規(guī)的查詢或插入等操作。
query_all():查詢多行數(shù)據(jù)脂男,并將其一次性返回一個元組养叛。
query_one():只查詢一行數(shù)據(jù)并將這一行數(shù)據(jù)以元組的形式返回。
close():關(guān)閉連接疆液。
我們可以通過創(chuàng)建MySQL類的實例一铅,并使用execute()或query_all()等方法來執(zhí)行SQL查詢或更新。例如堕油,下面的示例代碼檢查了一個用戶是否存在:
mysql = MySQL('localhost', 3306, 'root', 'password', 'database')
sql = 'SELECT * FROM users WHERE username = %s'
params = ('john',)
result = mysql.query_all(sql, params)
if len(result) > 0:
print('用戶已存在')
else:
print('可以創(chuàng)建用戶')
mysql.close()
需要注意的是潘飘,在執(zhí)行多條查詢操作時肮之,建議使用完query_all()方法后,使用close()方法關(guān)閉連接以釋放資源卜录。