如何将 Python 列表插入 SQL 行
How to insert a Python list into SQL Row
我试图将值列表插入到单个列中,但出现以下错误:
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
应该只包含查询,但您在其中也指定了 data
,所以最终您指定了两次 data
。
要么这样做:
data = '[12, 37]'
sqlpoptable = "INSERT INTO datas (conditions) VALUES (?);"
cursor.execute(sqlpoptable, data)
或者这个(语义等价,只是使用了一点语法糖):
data = '[12, 37]'
sqlpoptable = ("INSERT INTO datas (conditions) VALUES (?);", data)
cursor.execute(*sqlpoptable)
顺便说一句:您不需要将尾随分号传递给 psycopg2。
您可以使用参数列表,例如
data = [[12],[37]]
cursor.executemany("INSERT INTO datas(conditions) VALUES (?)",(data))
postgresConnection.commit()
其中 executemany
是比 execute
更高效的方法
我试图将值列表插入到单个列中,但出现以下错误:
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
应该只包含查询,但您在其中也指定了 data
,所以最终您指定了两次 data
。
要么这样做:
data = '[12, 37]'
sqlpoptable = "INSERT INTO datas (conditions) VALUES (?);"
cursor.execute(sqlpoptable, data)
或者这个(语义等价,只是使用了一点语法糖):
data = '[12, 37]'
sqlpoptable = ("INSERT INTO datas (conditions) VALUES (?);", data)
cursor.execute(*sqlpoptable)
顺便说一句:您不需要将尾随分号传递给 psycopg2。
您可以使用参数列表,例如
data = [[12],[37]]
cursor.executemany("INSERT INTO datas(conditions) VALUES (?)",(data))
postgresConnection.commit()
其中 executemany
是比 execute