[英]How to insert a Python list into SQL Row
I am trying to insert a list of values into a single column and getting the following error:我正在尝试将值列表插入单个列并收到以下错误:
postgresConnection = psycopg2.connect(
host='x',
user='x',
password='x',
database='x'
)
data = '[12, 37]'
sqlpoptable = ("INSERT INTO datas (conditions) VALUES (?);", data)
cursor.execute(sqlpoptable, data)
postgresConnection.commit()`
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-36-fa661d7bfe6a> in <module>
7 data = '[12, 37]'
8 sqlpoptable = ("INSERT INTO datas (conditions) VALUES (?);", data)
----> 9 cursor.execute(sqlpoptable, data)
10 postgresConnection.commit()
TypeError: argument 1 must be a string or unicode object: got tuple instead
sqlpoptable
should contain the query only, but you specified the data
in it, too, so eventually you specified data
twice. sqlpoptable
应该只包含查询,但是您也指定了其中的data
,因此最终您指定了两次data
。
Either do this:要么这样做:
data = '[12, 37]'
sqlpoptable = "INSERT INTO datas (conditions) VALUES (?);"
cursor.execute(sqlpoptable, data)
or this (semantically equivalent, just using a bit of syntactic sugar):或者这个(语义上等价,只是使用了一点语法糖):
data = '[12, 37]'
sqlpoptable = ("INSERT INTO datas (conditions) VALUES (?);", data)
cursor.execute(*sqlpoptable)
BTW: You do not need to pass a trailing semicolon to psycopg2.顺便说一句:您不需要将尾随分号传递给 psycopg2。
You can use a list for parameters such as您可以将列表用于参数,例如
data = [[12],[37]]
cursor.executemany("INSERT INTO datas(conditions) VALUES (?)",(data))
postgresConnection.commit()
where executemany
is more performant method than execute
其中
executemany
是比execute
更高效的方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.