在Python中从列表迭代插入表值

2024-09-28 05:20:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从结果列表中迭代,并尝试在exdata表中插入值,但我到处寻找解决方案,但没有任何结果对我有效

if not result:
    print 'list is empty'
else:
    for i in xrange(0,len(result)):
        for item  in  result[i].iteritems():
            query="INSERT INTO exdata (cve_id,severity, published,modified) \
                   VALUES ('%s', '%s', '%s', '%s')" % (item[i], item[1][0],item[1][1],item[1][2])
        cursor.execute(query)

Tags: in列表forifisnotresult解决方案
3条回答

如果使用MySQLdb并希望执行多行插入, 尝试使用executemany

import MySQLdb

db = MySQLdb.connect("myhost", "myuser", "mysecret", "mydb")
# users is a list of (userid, first_name, last_name, company)
c = db.cursor()
c.executemany("""INSERT INTO users
(userid, first_name, last_name, company)
VALUES (%s, %s, %s, %s)""", users)
db.commit()
db.close()

在MySQLdb中,这在内部被转换为一个多行INSERT,据报告它是2-3个顺序的 速度更快。在

您必须调用commit将值实际插入到数据库。
还要注意,execute在内部循环之外,因此它将只执行上一次迭代的查询。在

if not result:
    print 'list is empty'
else:
    for i in xrange(0,len(result)):
        for item  in  result[i].iteritems():
            query="INSERT INTO exdata (cve_id,severity, published,modified) \
                   VALUES ('%s', '%s', '%s', '%s')" % (item[i], item[1][0],item[1][1],item[1][2])
            cursor.execute(query)

            cursor.commit()

我在你的代码中看到两个问题:

1)需要执行循环查询
2) 添加用于修复更改的提交语句

if not result:
    print 'list is empty'
else:
    for i in xrange(0,len(result)):
        for item  in  result[i].iteritems():
            query="INSERT INTO exdata (cve_id,severity, published,modified) \
                   VALUES ('%s', '%s', '%s', '%s')" % (item[i], item[1][0],item[1][1],item[1][2])
            cursor.execute(query)
        connection.commit()

相关问题 更多 >

    热门问题