【问题标题】:How to load the JSON file too the PSQL database如何将 JSON 文件也加载到 PSQL 数据库中
【发布时间】:2018-12-12 05:43:29
【问题描述】:

我有一个 JSON 文件。现在我需要将 JSON 数据加载到我的 PSQL 数据库中。

目前我试过这个

import psycopg2
import json
with open('new.json') as f:
    data = f.read()
    dd = json.loads(data)
    conn = psycopg2.connect(database="newdb", user = "postgres",  password = "postgres",host = "127.0.0.1", port = "5432")

    print "Opened database successfully"

    cur = conn.cursor()

    cur.execute(''' CREATE TABLE jsontable(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"


    cur.execute('''INSERT INTO jsontable(data)
                   VALUES(%s)
                ''',
                     (data, 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()

请提供一些例子,如何将JSON文件数据传递到数据库

【问题讨论】:

  • 您创建的表与您插入值的表不同
  • 假设我需要将我的 JSON 文件数据插入到同一个表中。我的 new.json 文件 ---------------> [{ "sum": 2102.0, "app": "java", "appId": "1234", "Domain_name": "医学”,“Domain_Id”:“20000123”},{“sum”:1800.0,“app”:“python”,“appId”:“37345”,“Domain_name”:“工程”,“Domain_Id”:“823445” }]

标签: python database python-3.x postgresql postgresql-9.5


【解决方案1】:

我个人喜欢asyncpg,因为它是完全异步的,特别是如果您使用的是 Python 3.x 并且基本上您需要做的就是将 await 放在同步命令的前面。

import asyncpg
import json
with open('new.json') as f:
    data = f.read()
    dd = json.loads(data)
    conn = await asyncpg.connect(database="newdb", user = "postgres",  password = "postgres",host = "127.0.0.1", port = "5432")    
    print "Opened database successfully"
    await con.execute(''' CREATE TABLE jsontable(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"


    await con.execute('''INSERT INTO jsontable(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")
await conn.commit()
await conn.close()

【讨论】:

  • 我使用的是python 2.7.15版本
  • 那你为什么在你的问题中包含 3.X?
  • 不过,你可以使用我那里的 PGSQL 语句
  • cur.execute('''INSERT INTO jsontable(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"]))) 类型错误:列表索引必须是整数,而不是 str
猜你喜欢
  • 2019-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-19
  • 1970-01-01
  • 2016-01-12
  • 1970-01-01
相关资源
最近更新 更多