要将原来的博客数据迁移到新建的表上。表结构不一样,需要一条一条的重新插入。
使用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() #关闭连接(套接字)
文章评论