2015-10-10 46 views
0

我试图从数据库中提取记录,对其中一个字段进行一些处理,然后将数据插回到数据库中。但是,我注意到脚本在一次插入成功后停止,即使插入到数据库中的记录数量多于其他记录。MySQL从Python插入停止

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)) 
+2

这是一个非常糟糕的做法,只是'除了'。尝试将其更改为可能在此处发生的特定异常。 – grael

回答

0

正如我理解你的代码,你有什么重复插入,所以你检索N条记录,但只有1个插入记录。你需要实现的一些sudo代码是。

While(cursor hasnext): 
    select row 

    manipulate 

    insert 

您已接近结果,但缺少最后一步。

编辑: 您不能在相同的id上插入id,因为您必须让db处理该id或仅更新该行。所以从插入查询中删除id可能会解决问题。下次还会检查它告诉很多的数据库日志。

+0

对不起,这是一个复制错误,一切都已经在循环中。 –

+0

代码是否会失败,并显示except块或? –

+0

代码不会与except块一起失败,它会在成功插入一条记录后停止。我尝试了for循环和while循环。 –