Python 使用psycopg2参数化SQL查询
我试图安全地将查询字符串和参数传递给psycopg2,但在将列表格式化到查询中时遇到了问题。在第一个文件中,我有一个要传递给另一个执行查询的函数的列和值列表Python 使用psycopg2参数化SQL查询,python,sql,postgresql,psycopg2,Python,Sql,Postgresql,Psycopg2,我试图安全地将查询字符串和参数传递给psycopg2,但在将列表格式化到查询中时遇到了问题。在第一个文件中,我有一个要传递给另一个执行查询的函数的列和值列表 columns = ['id', 'name', 'address'] values = ['1234', 'john', '123 road'] query = """INSERT INTO table %s VALUES (%s)""" parameters = (tuple(
columns = ['id', 'name', 'address']
values = ['1234', 'john', '123 road']
query = """INSERT INTO table %s VALUES (%s)"""
parameters = (tuple(columns), tuple(values))
res = update(query, parameters)
在第二个文件中,我获取查询字符串和参数并执行它们:
def update(query_string: str, query_parameters: tuple):
with db.transaction() as txn:
txn.execute(query_string, query_parameter)
但我得到一个错误,说:
LINE 1: INSERT INTO table ('id', 'name', 'address')...
^
Syntax Error
将列和值列表传递到查询字符串中的正确方法是什么?我建议查看这些链接,了解有关如何使用psycopg动态生成SQL的更多详细信息:
- 主页:
- 第节:
def update(query_string: str, query_parameters: tuple):
with db.transaction() as txn:
txn.execute(query_string, query_parameter)
tableName = "your_table_name"
columns = ["id", "name", "address"]
values = ["1234", "john", "123 road"]
sql_insert_command = sql.SQL("""INSERT INTO {} ({}) VALUES {}""").format(
sql.Identifier(tableName),
sql.SQL(', ').join(map(sql.Identifier, columns)),
sql.SQL(', ').join(sql.Placeholder()*len(values)))
update(sql_insert_command, values)
列是标识符,不能使用参数替换。在文档中,请查看实现此目的的方法。您尝试过我的答案吗?如果它不起作用,请向我提供您遇到的错误或问题。@Lifeiscomplex我们最终使用了另一个不涉及使用psycopg2的解决方案。谢谢你!在
psycopg2
中没有带有执行值()的insert\u records\u,因此这不是使用psycopg2
的方法。有关内置方式,请参见。也没有提到tableName
的来源。如果你发布了一个答案,请让它足够有用。@AdrianKlaver我更新了我的答案。在我的数据库连接代码中,insert_records_with_execute_values()已链接到此psycopg2.extras.execute_值。您仍然没有处理需要动态添加列名的操作。省去很多麻烦,看看我之前发送的链接。它通过一个内置过程解决了所有这些问题。