我正在尝试从数据库中提取记录,对其中一个字段进行一些处理,然后将数据插入回数据库中。但是,我注意到脚本在一次成功插入后停止,即使除了插入到数据库中的记录之外还有更多记录。
cur = db.cursor()
# Pull records from the database, process each one, and store back into the database
SQLQuery = """SELECT * FROM cybersecurity4.hackhoundposts"""
cur.execute(SQLQuery)
for row in cur:
postID = row[0]
threadID = row[1]
authorID = row[2]
url = row[3]
subforum = row[4]
threadTitle = row[5]
authorName = row[6]
postDateTime = row[7]
postSequence = row[8]
flatcontent = row[9]
userTitle = row[11]
hasAttachment = row[12]
print (postID)
# #process the flatcontent
flatcontent = rmvSpecialCharsandCamelCase(flatcontent)
# insert into the database
try:
string = """INSERT INTO cybersecurity4.cleanedhackhoundposts
(postid, threadid, authorid, URL, subforum, threadTitle, authorName, postdatetime, postSequence, flatcontent, usertitle, hasattachment)
VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s','%s', '%s', '%s', '%s');""" % \
(postID ,threadID,authorID,url,subforum,threadTitle,authorName,postDateTime,postSequence,flatcontent,userTitle,hasAttachment)
print (string)
cur.execute(string)
print ("Successfully inserted post " + str(postID))
except:
int("Failed to insert post" + str(postID))
最佳答案
据我了解您的代码,您没有任何重复插入的内容,因此您正在检索 N 条记录,但只插入 1 条记录。您需要实现的一些 sudo 代码是。
While(cursor hasnext):
select row
manipulate
insert
您已经接近结果,但错过了最后的步骤。
编辑: 您不能在选择的同一 ID 上插入 id,您必须让数据库处理该 id 或仅更新该行。因此,从插入查询中删除 id 可能会解决问题。下次还要检查数据库日志,它会告诉您很多信息。
关于python - MySQL 从 Python 插入停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33059311/