【问题标题】:MySQL inserts stop from PythonMySQL 插入从 Python 停止
【发布时间】:2015-10-10 21:49:24
【问题描述】:

我正在尝试从数据库中提取记录,对其中一个字段进行一些处理,然后将数据插入回数据库中。但是,我注意到脚本在一次成功插入后停止,即使除了插入到数据库中的记录之外还有更多记录。

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

【问题讨论】:

  • 只做except 是一个非常糟糕的做法。尝试将其更改为此处可能发生的特定异常。

标签: python mysql pymysql


【解决方案1】:

据我了解您的代码,您没有重复插入,因此您正在检索 N 条记录,但只插入 1 条记录。您需要实现的一些 sudo 代码是。

While(cursor hasnext):
    select row

    manipulate

    insert

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

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

【讨论】:

  • 很抱歉这是一个复制错误,一切都已经在循环中了。
  • 代码不会因 except 块而失败,它只是在成功插入一条记录后停止。我用 for 循环和 while 循环都试过了。
  • 你确定 for 循环运行不止一次吗?
  • 是的,当我执行简单的任务时,例如打印 postID(每条记录都有一个),它会打印出所有记录的每个 postID。但是当我尝试重新插入数据库时​​,就像我正在尝试做的那样,没有运气。
  • 我正在将处理后的记录插入到一​​个新表中,与我从中提取数据的表分开。
猜你喜欢
  • 1970-01-01
  • 2011-02-03
  • 1970-01-01
  • 2013-01-31
  • 2015-08-20
  • 1970-01-01
  • 1970-01-01
  • 2011-12-23
  • 2017-01-07
相关资源
最近更新 更多