【问题标题】:How to insert a dictionary into Postgresql Table with Pscycopg2如何使用 Pscycopg2 将字典插入 Postgresql 表
【发布时间】:2018-08-10 03:43:40
【问题描述】:

如何将 python 字典插入 Postgresql2 表?我不断收到以下错误,因此我的查询格式不正确:

“至”第 1 行或附近的错误语法错误:INSERT INTO bill_summary VALUES(指定...的设施...

import psycopg2
import json
import psycopg2.extras
import sys
with open('data.json', 'r') as f:
        data = json.load(f)
con = None
try:
    con = psycopg2.connect(database='sanctionsdb', user='dbuser') 
    cur = con.cursor(cursor_factory=psycopg2.extras.DictCursor)
    cur.execute("CREATE TABLE bill_summary(title VARCHAR PRIMARY KEY, summary_text VARCHAR, action_date VARCHAR, action_desc VARCHAR)")
    for d in data:
        action_date = d['action-date']
        title = d['title']
        summary_text = d['summary-text']
        action_date = d['action-date']
        action_desc = d['action-desc']
        q = "INSERT INTO bill_summary VALUES(" +str(title)+str(summary_text)+str(action_date)+str(action_desc)+")"
        cur.execute(q)
    con.commit()

except psycopg2.DatabaseError, e:

    if con:
        con.rollback()

    print 'Error %s' % e    
    sys.exit(1)
finally:

    if con:
        con.close()

【问题讨论】:

  • 引用您的VALUES 输入

标签: python postgresql psycopg2


【解决方案1】:

您应该使用字典作为cursor.execute() 的第二个参数。见此语句后的示例代码in the documentation:

在查询中使用 %(name)s 占位符并将值指定到映射中也支持命名参数。

所以你的代码可能就这么简单:

with open('data.json', 'r') as f:
    data = json.load(f)

print(data)

""" above prints something like this:

{'title': 'the first action', 'summary-text': 'some summary', 'action-date': '2018-08-08', 'action-desc': 'action description'}

use the json keys as named parameters:
"""

cur = con.cursor()
q = "INSERT INTO bill_summary VALUES(%(title)s, %(summary-text)s, %(action-date)s, %(action-desc)s)"
cur.execute(q, data)
con.commit()

还要注意这个警告(from the same page of the documentation)

警告:从不、从不、从不使用 Python 字符串连接 (+) 或字符串参数插值 (%) 将变量传递给 SQL 查询字符串。甚至在枪口下也没有。

【讨论】:

    【解决方案2】:
     q = "INSERT INTO bill_summary VALUES(" +str(title)+str(summary_text)+str(action_date)+str(action_desc)+")" 
    

    您以错误的方式编写查询,通过连接值,它们应该是逗号分隔的元素,如下所示:

    q = "INSERT INTO bill_summary VALUES({0},{1},{2},{3})".format(str(title), str(summery_text), str(action_date),str(action_desc)) 
    

    由于您没有指定列名,我已经假设它们的顺序与您在插入查询中写入值的顺序相同。在 postgresql 中基本上有两种编写插入查询的方法。一种是通过指定列名及其对应的值,如下所示:

    INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)
    VALUES (value1, value2, value3,...valueN);
    

    另一种方法是,如果要为表的所有列添加值,则可能不需要在 SQL 查询中指定列名。但是,请确保值的顺序与表中列的顺序相同。您在查询中使用的,如下所示:

    INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);
    

    【讨论】:

    • 请不要将字符串插值作为构建查询字符串的方法。请参阅接受的答案以了解正确的做法。
    猜你喜欢
    • 2016-12-17
    • 1970-01-01
    • 2022-10-18
    • 2012-04-03
    • 2020-03-04
    • 2013-08-17
    • 2019-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多