python连接MySQL和postgreSQL,操作数据库,批量向数据库插入数据;
import psycopg2
import pymysql
# 连接PostgreSQL
def connect_postgresql():
conn = psycopg2.connect(
dbname="your_dbname",
user="your_username",
password="your_password",
host="your_host",
port="your_port"
)
return conn
# 连接MySQL
def connect_mysql():
conn = pymysql.connect(
host="your_host",
user="your_username",
password="your_password",
db="your_dbname",
charset='utf8mb4'
)
return conn
# 向PostgreSQL批量插入数据
def insert_data_postgresql(data):
conn = connect_postgresql()
cur = conn.cursor()
for row in data:
cur.execute("INSERT INTO your_table (column1, column2) VALUES (%s, %s)", row)
conn.commit()
conn.close()
# 向MySQL批量插入数据
def insert_data_mysql(data):
conn = connect_mysql()
cur = conn.cursor()
for row in data:
cur.execute("INSERT INTO your_table (column1, column2) VALUES (%s, %s)", row)
conn.commit()
conn.close()
# 示例数据
data_postgresql = [(1, 'Alice'), (2, 'Bob')]
data_mysql = [(3, 'Charlie'), (4, 'David')]
# 执行批量插入
insert_data_postgresql(data_postgresql)
insert_data_mysql(data_mysql)
在这个例子中,我们定义了两个函数connect_postgresql
和connect_mysql
来分别连接PostgreSQL和MySQL数据库。然后定义了两个函数insert_data_postgresql
和insert_data_mysql
来批量向对应的数据库表中插入数据。最后,我们使用示例数据执行了这两个函数。在实际应用中,你需要替换your_dbname
, your_username
, your_password
, your_host
, your_port
, your_table
, column1
, column2
以及data
变量的内容。
评论已关闭