【发布时间】:2019-04-24 13:56:58
【问题描述】:
我正在尝试使用psycopg2 生成动态INSERT INTO 语句,其中表、列和值都是动态的。
我已经阅读了有关psycopg2.SQL class 的文档,其中提供了一些提示,但我无法得到最终结果。
# inputs to the DB. Keys represent COLS. 2 records.
kvalues = [{'first':11,'second':22},{'first':33,'second':44}]
table = 'my_table'
columns = list(kvalues[0].keys())
values = [list(kvalue.values()) for kvalue in kvalues]
# Generate SQL string
conn = psycopg2.connect(#...details..)
cur = conn.cursor()
query_string = sql.SQL("INSERT INTO {} ({}) VALUES %s").format(
sql.Identifier(table),
sql.SQL(', ').join(map(sql.Identifier, columns))).as_string(cur)
print(cur.mogrify(query_string, values))
#>> TypeError: not all arguments converted during string formatting
我尝试在 SQL 语句中添加值,但这也会产生更多错误。
我怎样才能生成一个动态插入语句来接受来自 kvalues 的 cols、vals?
谢谢!
【问题讨论】:
标签: python postgresql psycopg2