如何使用pymysql连接多个数据库

整体流程

首先我们需要导入pymysql模块,然后按照以下步骤进行操作:

classDiagram
    class pymysql
    class pymysql.connections
    class pymysql.cursors
    class pymysql.err
  1. 建立连接:连接到第一个数据库;
  2. 执行操作:在第一个数据库上执行相关操作;
  3. 切换数据库:连接到第二个数据库;
  4. 执行操作:在第二个数据库上执行相关操作。

具体步骤

步骤一:建立第一个数据库连接

import pymysql

# 建立第一个数据库连接
conn1 = pymysql.connect(host='localhost', user='root', password='123456', database='database1')

步骤二:执行第一个数据库操作

# 获取游标
cursor1 = conn1.cursor()

# 执行查询操作
cursor1.execute("SELECT * FROM table1")

# 获取查询结果
result1 = cursor1.fetchall()

# 关闭游标
cursor1.close()

# 关闭连接
conn1.close()

步骤三:切换到第二个数据库连接

# 建立第二个数据库连接
conn2 = pymysql.connect(host='localhost', user='root', password='123456', database='database2')

步骤四:执行第二个数据库操作

# 获取游标
cursor2 = conn2.cursor()

# 执行查询操作
cursor2.execute("SELECT * FROM table2")

# 获取查询结果
result2 = cursor2.fetchall()

# 关闭游标
cursor2.close()

# 关闭连接
conn2.close()

通过以上步骤,你就可以成功连接多个数据库并执行相应操作了。记得在每次操作结束后关闭游标和连接,以释放资源。

希望以上内容能够帮助到你,如果有其他问题欢迎随时向我咨询。祝学习顺利!