利用Python封裝MySQLHelper類實現(xiàn)數(shù)據(jù)庫的增刪改查功能
Python 連接 MySQL 的方法有很多,常用的有 pymysql 和 mysql-connector-python 兩種庫。本文介紹使用 pymysql 庫連接 MySQL,并實現(xiàn)基本的增刪改查操作。
在使用 pymysql 前需要先安裝該庫,可使用 pip 命令進(jìn)行安裝:
pip install pymysql
首先,我們可以封裝一個 MySQLHelper 類來管理數(shù)據(jù)庫連接和操作:
import pymysql class MySQLHelper: def __init__(self, host, port, user, password, database): self.host = host self.port = port self.user = user self.password = password self.database = database self.conn = pymysql.connect(host=host, port=port, user=user, password=password, database=database) def execute(self, sql: str, params: tuple = None): """執(zhí)行 SQL 語句,無返回值""" cursor = self.conn.cursor() cursor.execute(sql, params or ()) self.conn.commit() cursor.close() def query_one(self, sql: str, params: tuple = None): """查詢并返回單條數(shù)據(jù)""" cursor = self.conn.cursor() cursor.execute(sql, params or ()) result = cursor.fetchone() cursor.close() return result def query_all(self, sql: str, params: tuple = None): """查詢并返回所有數(shù)據(jù)""" cursor = self.conn.cursor() cursor.execute(sql, params or ()) result = cursor.fetchall() cursor.close() return result def insert(self, table, data: dict): """插入一條數(shù)據(jù)""" fields = ','.join(data.keys()) values = ','.join(['%s'] * len(data)) sql = 'INSERT INTO %s (%s) VALUES (%s)' % (table, fields, values) self.execute(sql, tuple(data.values())) def update(self, table, data: dict, where: str = '1=2', where_params: tuple = None): """更新數(shù)據(jù)""" set_values = ','.join(['%s=%s' % (field, '%s') for field in data.keys()]) sql = 'UPDATE %s SET %s WHERE %s' % (table, set_values, where) params = tuple(data.values()) if where_params: params += where_params self.execute(sql, params) def delete(self, table, where: str = '1=2', where_params: tuple = None): """刪除數(shù)據(jù)""" sql = 'DELETE FROM %s WHERE %s' % (table, where) if where_params: self.execute(sql, where_params) else: self.execute(sql) def close(self): """關(guān)閉數(shù)據(jù)庫連接""" self.conn.close()
以上 MySQLHelper 類封裝了基本的增刪改查操作,說明如下:
execute
方法用于執(zhí)行 SQL 語句,無返回值;query_one
方法用于查詢并返回單條數(shù)據(jù);query_all
方法用于查詢并返回所有數(shù)據(jù);insert
方法用于插入一條數(shù)據(jù);update
方法用于更新數(shù)據(jù);delete
方法用于刪除數(shù)據(jù);close
方法用于關(guān)閉數(shù)據(jù)庫連接。
在使用 MySQLHelper 類時,需要先實例化一個對象,并傳遞數(shù)據(jù)庫連接參數(shù)。以下是一個簡單的示例:
if __name__ == '__main__': helper = MySQLHelper('localhost', 3306, 'root', 'your_password', 'mydatabase') helper.insert('mytable', {'column1': 'value1', 'column2': 'value2'}) helper.update('mytable', {'column1': 'new_value'}, 'id=%s', (1,)) helper.delete('mytable', 'id=%s', (1,)) result = helper.query_one('SELECT column1 FROM mytable WHERE id=%s', (1,)) helper.close()
以上示例代碼使用 MySQLHelper 連接到名為 mydatabase 的數(shù)據(jù)庫,并操作名為 mytable 的表。具體實現(xiàn)了數(shù)據(jù)庫的增、刪、改、查等功能。執(zhí)行完畢后,還需調(diào)用 close
方法關(guān)閉數(shù)據(jù)庫連接。
總體而言,使用 Python 和 pymysql 庫連接和操作 MySQL 數(shù)據(jù)庫非常簡單方便,可以輕松地完成各種數(shù)據(jù)庫操作任務(wù)。
到此這篇關(guān)于利用Python封裝MySQLHelper類實現(xiàn)數(shù)據(jù)庫的增刪改查功能的文章就介紹到這了,更多相關(guān)Python數(shù)據(jù)庫增刪改查內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python控制多進(jìn)程與多線程并發(fā)數(shù)總結(jié)
本篇文章主要介紹了Python控制多進(jìn)程與多線程并發(fā)數(shù),詳細(xì)講訴了進(jìn)程和線程的區(qū)別,并介紹了處理方法,有需要的朋友可以了解一下。2016-10-10解決python DataFrame 打印結(jié)果不換行問題
這篇文章主要介紹了解決python DataFrame 打印結(jié)果不換行問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04