如何通过Python连接不同类型的数据库(如MySQL、PostgreSQL、SQLite)并执行统一的SQL查询?请设计一个通用的数据库操作模块。

在设计一个通用的数据库操作模块时,可以通过Python的数据库API(如pymysql、psycopg2、sqlite3等)来实现对不同类型数据库的统一操作。以下是一个详细的通用模块设计示例,包含连接管理、SQL执行和异常处理等功能。

1. 使用标准库或第三方库

Python对不同数据库提供了不同的库支持:

  • MySQL: pymysql
  • PostgreSQL: psycopg2
  • SQLite: sqlite3(Python内置)

2. 设计通用模块

以下是一个通用的Database类,支持MySQL、PostgreSQL和SQLite:

import pymysql
import psycopg2
import sqlite3
from typing import Dict, List, Any, Optional


class Database:
    def __init__(self, db_type: str, **kwargs):
        """
        初始化数据库连接
        :param db_type: 数据库类型(mysql/postgresql/sqlite)
        :param kwargs: 连接参数(如host, user, password, database等)
        """
        self.db_type = db_type
        self.connection = None

        if db_type == "mysql":
            self.connection = pymysql.connect(**kwargs)
        elif db_type == "postgresql":
            self.connection = psycopg2.connect(**kwargs)
        elif db_type == "sqlite":
            self.connection = sqlite3.connect(kwargs.get("database"))
        else:
            raise ValueError("Unsupported database type")

    def execute_query(self, sql: str, params: Optional[tuple] = None) -> List[Dict[str, Any]]:
        """
        执行查询SQL并返回结果(字典形式)
        :param sql: SQL语句
        :param params: SQL参数
        :return: 查询结果列表(字典形式)
        """
        cursor = self.connection.cursor()
        try:
            cursor.execute(sql, params)
            columns = [col[0] for col in cursor.description]
            rows = cursor.fetchall()
            return [dict(zip(columns, row)) for row in rows]
        except Exception as e:
            print(f"Error executing query: {e}")
            return []
        finally:
            cursor.close()

    def execute_update(self, sql: str, params: Optional[tuple] = None) -> int:
        """
        执行更新SQL(INSERT/UPDATE/DELETE)
        :param sql: SQL语句
        :param params: SQL参数
        :return: 受影响的行数
        """
        cursor = self.connection.cursor()
        try:
            cursor.execute(sql, params)
            self.connection.commit()
            return cursor.rowcount
        except Exception as e:
            self.connection.rollback()
            print(f"Error executing update: {e}")
            return 0
        finally:
            cursor.close()

    def close(self):
        """关闭数据库连接"""
        if self.connection:
            self.connection.close()
            self.connection = None


# 示例使用
if __name__ == "__main__":
    # MySQL示例
    mysql_db = Database(
        db_type="mysql",
        host="localhost",
        user="root",
        password="123456",
        database="test_db"
    )
    results = mysql_db.execute_query("SELECT * FROM users WHERE age > %s", (20,))
    print(f"MySQL查询结果: {results}")
    mysql_db.close()

    # PostgreSQL示例
    postgres_db = Database(
        db_type="postgresql",
        host="localhost",
        user="postgres",
        password="123456",
        database="test_db"
    )
    results = postgres_db.execute_query("SELECT * FROM users WHERE age > %s", (20,))
    print(f"PostgreSQL查询结果: {results}")
    postgres_db.close()

    # SQLite示例
    sqlite_db = Database(db_type="sqlite", database="test.db")
    results = sqlite_db.execute_query("SELECT * FROM users WHERE age > ?", (20,))
    print(f"SQLite查询结果: {results}")
    sqlite_db.close()

3. 模块功能说明

  1. 初始化连接:通过__init__方法,根据数据库类型选择对应的连接库(如pymysql、psycopg2、sqlite3)。
  2. 执行查询:execute_query方法执行查询SQL,并将结果转换为字典列表格式。
  3. 执行更新:execute_update方法执行增删改操作,并返回受影响的行数。
  4. 异常处理:捕获数据库操作中的异常,打印错误信息并回滚事务(如PostgreSQL和MySQL)。
  5. 关闭连接:close方法显式关闭数据库连接,避免资源泄漏。

4. 注意事项

  • SQL参数化:使用参数化查询避免SQL注入(如MySQL使用%s,PostgreSQL使用%s,SQLite使用?)。
  • 事务管理:对于更新操作(如INSERT/UPDATE/DELETE),需要手动提交或回滚事务。
  • 性能优化:频繁操作时,可以考虑使用连接池(如DBUtils库)。

5. 扩展性

此模块可以进一步扩展,例如:

  • 支持连接池管理
  • 增加批量插入功能
  • 支持更复杂的SQL构建(如ORM风格查询)

通过这种方式,可以以统一的方式操作不同类型的数据库,减少代码冗余和维护成本。