2015-10-10 43 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循環。 –