在PYCHARM里为我设计一个接口连接两个不同的MYSQL数据库,要求增删改查
时间: 2024-09-24 14:16:35 浏览: 59
Python Sql数据库增删改查操作简单封装
在PyCharm中设计一个能够连接并操作两个不同MySQL数据库的接口,可以采用以下步骤和Python库,例如使用`pymysql`库来实现基本的数据库操作,加上一些封装来提供增删改查的功能。这里假设你已经有一个基础的数据库连接模块(如`db_1`和`db_2`分别对应两个数据库):
```python
import pymysql
class DualDBHandler:
def __init__(self):
# 初始化两个数据库连接
self.conn1 = pymysql.connect(host='localhost', user='user1', password='password1', db='database1')
self.conn2 = pymysql.connect(host='localhost', user='user2', password='password2', db='database2')
# 定义增删改查的基本方法
def insert_data(self, table_name, data, db_index=0):
if db_index == 0:
with self.conn1.cursor() as cursor:
sql = "INSERT INTO {} VALUES {}".format(table_name, data)
cursor.execute(sql)
self.conn1.commit()
elif db_index == 1:
with self.conn2.cursor() as cursor:
sql = "INSERT INTO {} VALUES {}".format(table_name, data)
cursor.execute(sql)
self.conn2.commit()
def delete_data(self, table_name, condition, db_index=0):
if db_index == 0:
with self.conn1.cursor() as cursor:
sql = "DELETE FROM {} WHERE {}".format(table_name, condition)
cursor.execute(sql)
self.conn1.commit()
else:
with self.conn2.cursor() as cursor:
sql = "DELETE FROM {} WHERE {}".format(table_name, condition)
cursor.execute(sql)
self.conn2.commit()
def update_data(self, table_name, set_values, where_condition, db_index=0):
if db_index == 0:
with self.conn1.cursor() as cursor:
sql = "UPDATE {} SET {} WHERE {}".format(table_name, set_values, where_condition)
cursor.execute(sql)
self.conn1.commit()
else:
with self.conn2.cursor() as cursor:
sql = "UPDATE {} SET {} WHERE {}".format(table_name, set_values, where_condition)
cursor.execute(sql)
self.conn2.commit()
def select_data(self, table_name, columns=None, where_condition=None, db_index=0):
if db_index == 0:
with self.conn1.cursor() as cursor:
query = "SELECT"
if columns:
query += " {},".format(columns)
query += " FROM {} ".format(table_name)
if where_condition:
query += "WHERE {}".format(where_condition)
cursor.execute(query)
return cursor.fetchall()
else:
with self.conn2.cursor() as cursor:
query = "SELECT"
if columns:
query += " {},".format(columns)
query += " FROM {} ".format(table_name)
if where_condition:
query += "WHERE {}".format(where_condition)
cursor.execute(query)
return cursor.fetchall()
# 使用示例
handler = DualDBHandler()
handler.insert_data('table1', ('value1', 'value2'), 0) # 插入到db1
handler.delete_data('table2', 'id = 1', 1) # 删除db2的记录
...
```
请注意,这只是一个基本的模板,实际应用中还需要考虑错误处理和资源管理。另外,对于复杂的多库操作,你可能会倾向于使用ORM框架(如SQLAlchemy)来简化工作流程。
阅读全文