把A数据库里的文章导入到B数据WordPress中,在WP6.7.2版本中测试通过
import pymysql
from datetime import datetime
# 数据库连接设置
db1 = pymysql.connect(
host="localhost",
user="root",
password="xxxxxxxxxxx",
database="xxxxxxxxxxxxx"
)
db2 = pymysql.connect(
host="192.168.1.50",
user="xxxxxxxxxxxxx",
password="xxxxxxxxxxxx",
database="xxxxxxxxxxxxxx"
)
# 获取当前时间
now = datetime.now()
formatted_date = now.strftime('%Y-%m-%d %H:%M:%S')
# 创建游标对象
cursor1 = db1.cursor()
cursor2 = db2.cursor()
# 获取events表中的数据
cursor1.execute("SELECT title, content FROM events")
events = cursor1.fetchall()
# 定义插入文章的函数
def insert_post(post_content, post_title, post_excerpt='', to_ping='', pinged='', post_content_filtered=''):
sql = """
INSERT INTO tmp1a6d65_posts (post_author, post_date, post_date_gmt, post_content, post_title, post_excerpt, to_ping, pinged, post_content_filtered)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
"""
try:
cursor2.execute(sql, (1, formatted_date, formatted_date, post_content, post_title, post_excerpt, to_ping, pinged, post_content_filtered))
db2.commit()
print("文章已成功插入到数据库")
except Exception as e:
db2.rollback()
print(f"插入数据时出错: {e}")
# 遍历events表中的数据,并插入到tmp1a6d65_posts表中
for event in events:
title, content = event
insert_post(content, title)
# 关闭数据库连接
cursor1.close()
db1.close()
cursor2.close()
db2.close()

评论