python - MySQL 从 Python 插入停止

标签 python mysql pymysql

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

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/

相关文章:

python - 如何从 FTP 服务器读取 gzip 文件?

python - python/numpy中的优雅网格搜索

python - 匹配两个不同的数组并在python中创建一个新数组

mysql - 远程数据库连接出现问题,可能是在解析主机名 ip 时

mysql - 使用 PyMySQL 时语法无效

python - argparse 可选位置参数和 subparsers 参数

php - 上传 PDF 文件并将文件名发送到数据库

Python 在我的查询参数中添加单引号

python - 如何获取 pymysql 连接的最后一个 sql errno?

mysql - 使用 nodejs 云函数将 csv 文件导入 Google CloudSQL