【问题标题】:psycopg2: dynamic table, columns and valuespsycopg2:动态表、列和值
【发布时间】: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


    【解决方案1】:

    问题在于元组/列表格式。以下是有效的代码:

    kvalues = [{'first':11,'second':22},{'first':33,'second':44}]
    
    table   = 'my_table'
    columns = list(kvalues[0].keys())
    values  = [tuple(kvalue.values()) for kvalue in kvalues]
    
    # Generate SQL string
    conn = psycopg2.connect(#...details..)
    cur  = conn.cursor()
    
    query_string = sql.SQL("INSERT INTO {} ({}) VALUES {}").format(
            sql.Identifier(table),
            sql.SQL(', ').join(map(sql.Identifier, columns)),
            sql.SQL(', ').join(sql.Placeholder()*len(values)),
            ).as_string(cur)
    
    print(cur.mogrify(query_string, values))
    

    【讨论】:

      猜你喜欢
      • 2017-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-09
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多