gpt4 book ai didi

python - 如何修复 '%' 处或附近的 psycopg2 语法错误?

转载 作者:行者123 更新时间:2023-12-01 00:11:24 28 4
gpt4 key购买 nike

基本上尝试创建 ISNERT 函数,该函数将编译插入并执行它。

def Insert(self,tablename, **kwargs):
qms = []
for idx, item in enumerate(kwargs):
qms.append('%%s')
qmarks = ', '.join(qms)
res = []
res.extend(kwargs.keys())
res.extend(kwargs.values())
res = tuple(res)
QUERY = "INSERT INTO "+tablename+" (%s) VALUES (%s)" % (qmarks, qmarks)
self.dc.execute(QUERY, res)
self.db.commit()

返回我:

psycopg2.errors.SyntaxError: syntax error at or near "%"
LINE 1: INSERT INTO users (%s, %s) VALUES (%s, %s)

最佳答案

psycopg2 的 execute() 函数仅注入(inject)值但不列,您需要将真实的列名称传递给 QUERY:

import psycopg2
import psycopg2.extras


class A():
def __init__(self):
self.dc = ...
self.db = ...

def Insert(self, tablename, **kwargs):
columns = []
valuePlaceholders = []
values = []
for column, value in kwargs.items():
columns.append(column)
valuePlaceholders.append('%%s')
values.append(value)

QUERY = "INSERT INTO " + tablename + " (%s) VALUES (%s)" % (', '.join(columns), ', '.join(valuePlaceholders))
print(self.db.mogrify(QUERY, values))
#self.db.execute(QUERY, values)
#self.db.commit()


a = A().Insert('foo', arg1="bar", arg2="test")

输出:

b'INSERT INTO foo (arg1, arg2) VALUES (%s, %s)'

关于python - 如何修复 '%' 处或附近的 psycopg2 语法错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59610256/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com