将 python 列表插入 Postgres 数据库
我在使用 psycopg 格式化插入列表时遇到问题。 这是我正在尝试执行的代码示例。 基本上我只是从一个表中读取数据并尝试将其插入到另一个表中。
代码:
cur.execute("""select data from \"Table1\" where lat=-20.004189 and lon=-63.848004""")
rows = cur.fetchall()
print rows
cur.execute("""INSERT INTO \"%s\" (data) VALUES (ARRAY%s)""" % (args.tableName,rows)))
第一个选择查询返回的结果如下:
[([6193, 3975, 4960, 5286, 3380, 970, 3328, 3173, 2897, 2457, 2443, 2674, 2172, 2740, 3738, 4907, 3691, 4234, 3651, 3215],)]
当我尝试将其插入到另一个表中时,出现以下格式错误。
cur.execute(cur.mogrify("""INSERT INTO \"%s\" (data) VALUES (%s)""" % (args.tableName,rows)))
psycopg2.ProgrammingError: syntax error at or near "["
LINE 1: INSERT INTO "DUMMY1km" (data) VALUES ([([6193, 3975, 4960, 5...
我尝试了 cur.mogrify,但它似乎没有帮助。
如果有人可以解决此问题,请告诉我。
谢谢 阿迪
I am having trouble in formatting the list for insertion using psycopg.
Here is a sample of code i am trying to do.
Basically I am just reading data from one table and trying to insert it into another table.
Code:
cur.execute("""select data from \"Table1\" where lat=-20.004189 and lon=-63.848004""")
rows = cur.fetchall()
print rows
cur.execute("""INSERT INTO \"%s\" (data) VALUES (ARRAY%s)""" % (args.tableName,rows)))
The result returned by first select query is like this:
[([6193, 3975, 4960, 5286, 3380, 970, 3328, 3173, 2897, 2457, 2443, 2674, 2172, 2740, 3738, 4907, 3691, 4234, 3651, 3215],)]
When I try to insert this into another table I get the following format error.
cur.execute(cur.mogrify("""INSERT INTO \"%s\" (data) VALUES (%s)""" % (args.tableName,rows)))
psycopg2.ProgrammingError: syntax error at or near "["
LINE 1: INSERT INTO "DUMMY1km" (data) VALUES ([([6193, 3975, 4960, 5...
I tried cur.mogrify, but it does not seem to help.
Please let me know if anyone has a work around for this issue.
Thanks
Adi
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为这里不需要
mogrify
。使用executemany
并传递rows
作为第二个参数。使用参数化参数有助于防止SQL 注入。
表名无法参数化,因此我们必须使用字符串插值将表名放入 SQL 查询中。
%%s
gets 转义百分号,字符串插值后变为%s
。顺便说一句,(正如 a_horse_with_no_name 已经指出的)您可以使用 INSERT INTO ... SELECT form of
INSERT
将两个 SQL 查询作为一个执行:根据注释中的问题,如果有多个字段,则SQL 变为:(
如果使用
format
方法,则不必转义所有其他%s
s。)I don't think
mogrify
is needed here. Useexecutemany
and passrows
as the second argument.Using parametrized arguments helps prevent SQL injection.
The table name can not be parametrized, so we do have to use string interpolation to place the table name in the SQL query.
%%s
gets escapes the percent sign and becomes%s
after string interpolation.By the way, (as a_horse_with_no_name has already pointed out) you can use the INSERT INTO ... SELECT form of
INSERT
to perform both SQL queries as one:Per the question in the comments, if there are multiple fields, then the SQL becomes:
(If you use the
format
method, then you don't have to escape all the other%s
s.)