如何使用python将JSON数据传递到PostgresSql数据库

时间:2018-12-12 10:56:02

标签: python-2.7 postgresql-9.5

我有一个JSON文件。我试图将JSON数据传递到PSQL

到目前为止,我已经尝试过

import psycopg2
import json
with open('jsondata.json') as f:
        data = f.read()
        dd= json.loads(data)

print(dd)
conn = psycopg2.connect(database="testdb", user = "postgres",  password = "postgres",host = "127.0.0.1", port = "5432")

print "Opened database successfully"
cur = conn.cursor()
cur.execute(''' CREATE TABLE test(SUM INT NOT NULL,
                                      APP  CHAR[30] NOT NULL,
                                                      ID INT NOT NULL,
                                                      DOMAINNAME TEXT NOT NULL,
                                      DOMAINID INT NOT NULL);''')
print "Table Created successfully"

print(type(data))
cur.execute("INSERT INTO test(SUM,APP,ID,DOMAINNAME,DOMAINID) VALUES($1,$2,$3,$4,$5)", (str(dd["sum"]),str(dd["app"]),str(dd["id"]),str(dd["Domain_name"]),str(dd["Domain_Id"])))
print "Data Entered successfully"
conn.commit()
conn.close()
print "connection closed successfully"

我收到此错误

cur.execute("INSERT INTO test(SUM,APP,ID,DOMAINNAME,DOMAINID) VALUES($1,$2,$3,$4,$5::json)", (str(dd["sum"]),str(dd["app"]),str(dd["id"]),str(dd["Domain_name"]),str(dd["Domain_Id"])))

TypeError:列表索引必须是整数,而不是str

我期待输出

Expecting table

0 个答案:

没有答案