[英]Populate Sqlite3 column with data from Python list using for loop
I am trying to use sqlite3 in Python by using a for loop to iterate through all the items in a list and populate a column with that data. 我试图通过使用for循环在列表中的所有项目中迭代并使用该数据填充列,从而在Python中使用sqlite3。 My code below will hopefully shed some light on the problem: 我的以下代码有望对该问题有所启发:
import sqlite3 as lite
test_run = ['tommy', 'olga', 'peter', 'lulu']
con = lite.connect("test.db")
cur = con.cursor()
cur.execute('DROP TABLE IF EXISTS test1;')
cur.execute('CREATE TABLE test1(symbol TEXT); ')
for i in test_run:
name = i
print name
cur.executemany('INSERT INTO test1 VALUES(?)',name)
with con:
cur = con.cursor()
cur.execute("SELECT * FROM test1")
rows = cur.fetchall()
for row in rows:
print row
I apologize if this is very basic, but I have just learned Python and this is my first time using SQL. 抱歉,这是非常基本的内容,但是我刚刚学习了Python,这是我第一次使用SQL。 When I print name it seems like this should work but when using fetchall to see what is being populated it appears as: 当我打印名称时,这似乎应该可以工作,但是当使用fetchall查看正在填充的内容时,它显示为:
(u't',)
(u'o',)
(u'm',)
(u'm',)
(u'y',)
(u'o',)
(u'l',)
I have read a lot of the answers here and this would seem to be the correct way to accomplish this. 我在这里阅读了很多答案,这似乎是实现此目的的正确方法。
I can identify following issues in your code. 我可以在您的代码中找出以下问题。
cur.executemany
is not in the loop. cur.executemany
不在循环中。 insert
query. 在insert
查询中只有一个参数要绑定。 No need to use cur.executemany
. 无需使用cur.executemany
。 tuple
. 将字符串参数绑定到查询时,应将字符串转换为tuple
。 I think the correct code might look like this - 我认为正确的代码可能看起来像这样-
for i in test_run:
name = (i,)
print i
cur.execute("INSERT INTO test1 VALUES(?)", name)
Also use con.commit()
after the insert query or you can't get the inserted rows after application termination. 还可以在插入查询之后使用con.commit()
,否则应用程序终止后将无法获得插入的行。 Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.