原创-python直接数据库入库文章代码

秋知德雨个人 2023-3-10 599 3/10

 

原创-python直接数据库入库文章代码

import pymysql

# 数据库连接信息
host = 'bj-cynosdcxvcxvcxvcxvdb.com'
port = 2019
user = 'root'
password = 'Wuf256669555@'
db = 'wpjson'
charset = 'utf8mb4'

# 连接数据库
connection = pymysql.connect(host=host, port=port, user=user, password=password, db=db, charset=charset)

try:
    with connection.cursor() as cursor:
        # 新建文章的标题和内容
        post_title = '测试文章'
        post_content = '这是一篇测试文章。'

        # 构造插入文章的SQL语句
        sql = "INSERT INTO wp_posts(post_author, post_date, post_date_gmt, post_content, post_title, post_excerpt, post_status, comment_status, ping_status, post_password, post_name, to_ping, pinged, post_modified, post_modified_gmt, post_content_filtered, post_parent, guid, menu_order, post_type, post_mime_type, comment_count) VALUES (%s, NOW(), NOW(), %s, %s, '', 'publish', 'open', 'open', '', %s, '', '', NOW(), NOW(), '', 0, %s, 0, 'post', '', 0)"

        # 插入文章数据
        cursor.execute(sql, (1, post_content, post_title, post_title, post_title))

        # 提交事务
        connection.commit()

        # 打印新插入的文章ID
        post_id = cursor.lastrowid
        print("插入新文章成功,文章ID为:", post_id)

        # 指定分类
        category_id = 1
        sql = "INSERT INTO wp_term_relationships(object_id, term_taxonomy_id, term_order) VALUES (%s, %s, 0)"
        cursor.execute(sql, (post_id, category_id))
        connection.commit()

        # 指定标签
        tag_names = "标签1,标签2,标签3"
        tag_names = tag_names.split(",")
        for tag_name in tag_names:
            # 查询标签是否存在,如果不存在就创建
            sql = "SELECT term_id FROM wp_terms WHERE name=%s"
            cursor.execute(sql, tag_name)
            result = cursor.fetchone()
            if result:
                tag_id = result[0]
            else:
                sql = "INSERT INTO wp_terms(name, slug) VALUES (%s, %s)"
                cursor.execute(sql, (tag_name, tag_name.lower().replace(" ", "-")))
                tag_id = cursor.lastrowid
                connection.commit()
                # 创建标签与分类法的关系
                sql = "INSERT INTO wp_term_taxonomy(term_id, taxonomy, description, parent) VALUES (%s, 'post_tag', '', 0)"
                cursor.execute(sql, (tag_id,))
                connection.commit()

            # 将标签与文章关联
            sql = "INSERT INTO wp_term_relationships(object_id, term_taxonomy_id, term_order) VALUES (%s, %s, 0)"

            cursor.execute(sql, (post_id, tag_id))
            connection.commit()
        print("文章分类和标签指定成功!")

except Exception as e:
    # 出现异常时回滚事务
    connection.rollback()
    print("插入新文章失败,错误信息为:", str(e))

finally:
    # 关闭数据库连接
    connection.close()

 

- THE END -

秋知德雨个人

3月11日22:24

最后修改:2023年3月11日
1

非特殊说明,本博所有文章均为博主原创。

共有 0 条评论