把A数据库里的文章导入到WordPress中

其他杂项30字数 1170阅读3分54秒阅读模式

把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()

 
  • 本文由 asdfasd 发表于 2025-02-1710:46:54
  • 转载请务必保留本文链接:http://wp.fangfa.me/other-note/%e6%8a%8aa%e6%95%b0%e6%8d%ae%e5%ba%93%e9%87%8c%e7%9a%84%e6%96%87%e7%ab%a0%e5%af%bc%e5%85%a5%e5%88%b0wordpress%e4%b8%ad.html