封装一个MySQLHelper 类,实现对数据库的增删改查功能

545 阅读2分钟

Python 连接 MySQL 的方法有很多,常用的有 pymysql 和 mysql-connector-python 两种库。本文介绍使用 pymysql 库连接 MySQL,并实现基本的增删改查操作。

在使用 pymysql 前需要先安装该库,可使用 pip 命令进行安装:

pip install pymysql

首先,我们可以封装一个 MySQLHelper 类来管理数据库连接和操作:

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):
        """执行 SQL 语句,无返回值"""
        cursor = self.conn.cursor()
        cursor.execute(sql, params or ())
        self.conn.commit()
        cursor.close()

    def query_one(self, sql: str, params: tuple = None):
        """查询并返回单条数据"""
        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):
        """查询并返回所有数据"""
        cursor = self.conn.cursor()
        cursor.execute(sql, params or ())
        result = cursor.fetchall()
        cursor.close()
        return result

    def insert(self, table, data: dict):
        """插入一条数据"""
        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):
        """更新数据"""
        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):
        """删除数据"""
        sql = 'DELETE FROM %s WHERE %s' % (table, where)
        if where_params:
            self.execute(sql, where_params)
        else:
            self.execute(sql)

    def close(self):
        """关闭数据库连接"""
        self.conn.close()

以上 MySQLHelper 类封装了基本的增删改查操作,说明如下:

  • execute 方法用于执行 SQL 语句,无返回值;
  • query_one 方法用于查询并返回单条数据;
  • query_all 方法用于查询并返回所有数据;
  • insert 方法用于插入一条数据;
  • update 方法用于更新数据;
  • delete 方法用于删除数据;
  • close 方法用于关闭数据库连接。

在使用 MySQLHelper 类时,需要先实例化一个对象,并传递数据库连接参数。以下是一个简单的示例:

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 的数据库,并操作名为 mytable 的表。具体实现了数据库的增、删、改、查等功能。执行完毕后,还需调用 close 方法关闭数据库连接。

总体而言,使用 Python 和 pymysql 库连接和操作 MySQL 数据库非常简单方便,可以轻松地完成各种数据库操作任务。