Python如何连接多个数据库的方案

在现代应用程序中,通常需要从多个数据库中读取和写入数据。Python作为一种强大的编程语言,提供了多种方式来连接和操作不同类型的数据库,如MySQL、PostgreSQL、SQLite等。本文将介绍如何使用Python连接多个数据库,并通过一个具体的方案来演示实现过程。

方案概述

本方案的目标是创建一个简单的应用程序,能够连接到MySQL和SQLite两个数据库,分别用于存储用户信息和日志信息。用户信息存储在MySQL数据库中,而日志信息将存储在SQLite数据库中。通过这种方式,即可以利用MySQL的强大特性,又可以利用SQLite的轻量特性。

环境准备

在开始编写代码之前,请确保你已经安装了以下Python库:

pip install mysql-connector-python sqlite3

数据库设计

我们将设计两个数据库表,一个用于MySQL用户信息表,另一个用于SQLite日志表。

用户表设计(MySQL)

字段 类型 描述
id INT 主键
username VARCHAR(50) 用户名
email VARCHAR(100) 邮箱地址

日志表设计(SQLite)

字段 类型 描述
id INTEGER 主键
user_id INT 用户ID
action TEXT 用户操作
timestamp DATETIME 操作时间

类图

以下是我们将要实现的类图:

classDiagram
    class User {
        +int id
        +String username
        +String email
        +void save()
    }
    class Log {
        +int id
        +int user_id
        +String action
        +datetime timestamp
        +void log_action()
    }
    User "1" -- "0..*" Log : creates

数据库连接及操作示例代码

以下是使用Python连接MySQL和SQLite的示例代码:

import mysql.connector
import sqlite3
from datetime import datetime

class User:
    def __init__(self, username, email):
        self.username = username
        self.email = email

    def save(self):
        # 连接MySQL数据库
        conn = mysql.connector.connect(
            host='localhost',
            user='your_user',
            password='your_password',
            database='your_database'
        )
        cursor = conn.cursor()
        cursor.execute("INSERT INTO users (username, email) VALUES (%s, %s)", (self.username, self.email))
        conn.commit()
        cursor.close()
        conn.close()

class Log:
    def __init__(self, user_id, action):
        self.user_id = user_id
        self.action = action
        self.timestamp = datetime.now()

    def log_action(self):
        # 连接SQLite数据库
        conn = sqlite3.connect('logs.db')
        cursor = conn.cursor()
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS logs (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                user_id INTEGER,
                action TEXT,
                timestamp DATETIME
            )
        ''')
        cursor.execute("INSERT INTO logs (user_id, action, timestamp) VALUES (?, ?, ?)",
                       (self.user_id, self.action, self.timestamp))
        conn.commit()
        cursor.close()
        conn.close()

# 使用示例
new_user = User('john_doe', 'john@example.com')
new_user.save()

new_log = Log(new_user.id, 'User has been created.')
new_log.log_action()

数据库关系图

以下是我们数据库之间关系的示意图:

erDiagram
    USER {
        INT id PK
        STRING username
        STRING email
    }
    LOG {
        INT id PK
        INT user_id FK
        STRING action
        DATETIME timestamp
    }
    
    USER ||--o{ LOG : creates

结论

通过上述方案,我们成功实现了一个连接多个数据库的Python应用程序。MySQL用于存储用户信息,而SQLite则用于记录用户操作的日志。借助Python丰富的库支持,我们可以轻松地在不同数据库之间进行操作和管理数据。这种多数据库的设计模式在实际开发中非常常见,可以极大地提高应用程序的灵活性和扩展性。希望本文的介绍能对你在实现多数据库连接时有所帮助。