清科谷体的博客

  • 文章
  • 关于
  • 联系
  • 隐私政策

  1. 首页
  2. 编程
  3. 正文

Python 操作数据库 跨表结构迁移数据

2024年12月12日 290点热度 0人点赞 0条评论

要将原来的博客数据迁移到新建的表上。表结构不一样,需要一条一条的重新插入。

使用pymysql模块,Python自动批量将数据迁移到不同表结构的新表上。

#导入mysql数据库驱动
import pymysql

#建立与数据库的连接
conn=pymysql.connect(host='localhost',user='root',password='123456789',database='blog_ingke_net')

#创建游标
cursor=conn.cursor()

sql1='SELECT ID, post_title, post_content, post_date, post_modified, post_status FROM wp_posts'
#执行sql语句
cursor.execute(sql1)
#fetchall()返回所有的查询结果,返回二维元组
res1 = cursor.fetchall()

cursor.close()  #关闭游标
conn.close()    #关闭连接(套接字)


#迁移数据
conn=pymysql.connect(host='localhost',user='root',password='123456789',database='blog_design')
cursor=conn.cursor()

id=0
title = content = postTime = updateTime = postStatu =''

sql2= '''
    INSERT INTO article(article_ID, article_title, article_content, post_time, update_time, post_status)
    VALUES (%s, %s, %s, %s, %s, %s)
'''
for row in res1:
    id=row[0]
    title=row[1]
    content=row[2]
    postTime=row[3].strftime('%Y-%m-%d %H:%M:%S')       #查询结果的时间是python的datetime类,转换为str字符串
    updateTime=row[4].strftime('%Y-%m-%d %H:%M:%S')     #查询结果的时间是python的datetime类,转换为str字符串
    postStatus=row[5]

    cursor.execute(sql2,(id, title, content, postTime, updateTime, postStatus))
     
conn.commit()   #提交才能修改数据库中记录(增、删、改必须要commit)
cursor.close()  #关闭游标
conn.close()    #关闭连接(套接字)

参考链接:博客园cnblogs-pymysql模块使用教程

本作品采用 知识共享署名 4.0 国际许可协议 进行许可
标签: MySQL Python 数据库
最后更新:2025年4月28日

ingker

自娱自乐

点赞
< 上一篇
下一篇 >

文章评论

取消回复

COPYRIGHT © 2026 清科谷体's blog. ALL RIGHTS RESERVED.
THEME KRATOS MADE BY VTROIS | MODIFIED BY INGKER

正在加载今日诗词....

本站已运行