【问题标题】:How to create new table and insert data in to table using python based on json如何使用基于json的python创建新表并将数据插入表中
【发布时间】:2021-02-01 13:53:16
【问题描述】:

我正在尝试创建一个新的数据库表并将数据插入到该表中。示例我有两个表数据,表列名称和列数据类型。我想创建这两个表并将数据插入到正确的表名中。我使用了带有连接参数的python函数。征求您的建议以实现这一目标。

json 数据

data_JSON =  """
[
    {
        "dbName": "sampledata",
        "tableName": [
            "status_in","status_out"
        ],
        "tableColumn": [
            [
                {
                    "type": "INT",
                    "title": "phoneno"
                },
                {
                    "type": "VARCHAR (60)",
                    "title": "name"
                },
                {
                    "type": "DATE",
                    "title": "date"
                }
            ],
            [
                {
                    "type": "INT",
                    "title": "phoneno"
                },
                {
                    "type": "VARCHAR (60)",
                    "title": "name"
                },
                {
                    "type": "DATE",
                    "title": "date"
                }
            ]
        ],
        "tableData": [
            [
                {
                    "phoneno": "99999",
                    "name": "ticker1",
                    "date": "01/01/2021"
                },
                {
                    "phoneno": "99999",
                    "name": "ticker2",
                    "date": "01/01/2021"
                },
                {
                    "phoneno": "99999",
                    "name": "ticker3",
                    "date": "01/01/2021"
                }
            ],
            [
                {
                    "phoneno": "99999",
                    "name": "few1",
                    "date": "01/01/2021"
                },
                {
                    "phoneno": "99999",
                    "name": "few2",
                    "date": "01/01/2021"
                },
                {
                    "phoneno": "99999",
                    "name": "few1",
                    "date": "01/01/2021"
                }
            ]
        ]
    }
]
"""

Python 代码

import json
import psycopg2
from psycopg2 import sql
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
def create_table(data_JSON):
    try:
        filedata = json.loads(data_JSON)
        db_name = filedata[0] ['dbname']
        con = psycopg2.connect(user='postgres', host='127.0.0.1', database = db_name, password='test@123')
        con.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
        cur = con.cursor()
        for sheet in data_dict[0]['tableName']:
            sheet_name = sheet   
        for z in data_dict[0]['tableColumn']:
            for column in z[0][title]:
                column_name = column
            for dtype in z[0]['type']:
                datatype = dtype
                cur.execute(f"CREATE TABLE {sheet_name}({column_name} {data_type});")
        for key,value in data_dict[0]['tableData']:
            cur.execute(f"INSERT INTO {sheet_name}({column_name})VALUES ({value});")
            con.commit()
            cur.close()
            con.close()
    except Exception:
        return False
    return True

【问题讨论】:

  • 这是一些代码。如果您遇到错误,请写下来:)
  • 我没有收到任何错误。
  • 因为你没有打印,尝试修改except Exception: return Falseexcept Exception as e: print(e)
  • 现在也没有显示错误...
  • 然后验证您的数据库

标签: python json psql


【解决方案1】:

你好, 我已经修改并测试了它。 这是重构的代码:


import json
import psycopg2
from psycopg2 import sql
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
def create_table(data_JSON):
    try:
        filedata = json.loads(data_JSON)
        db_name = filedata[0]['dbName']
        print(db_name)
        
        con = psycopg2.connect(user='postgres', host='127.0.0.1', database = db_name, password='password')
        print ("Opened database successfully")
        con.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
        cur = con.cursor()
        table_names = filedata[0]['tableName'] 
        table_columns = filedata[0]['tableColumn']
        table_datum = filedata[0]['tableData']
        for table_name, table_column, table_data in zip(table_names, table_columns, table_datum):
            column_to_insert = ""
            for td in table_column:
                column_to_insert += td['title'] + " " + td['type'] +", "
            
            column_to_insert = column_to_insert[:len(column_to_insert) - 2]
            cur.execute(f"CREATE TABLE {table_name} ({column_to_insert});")
        
            for row in table_data:
                
                keys = ", ".join(row.keys())
                values = ""
                for val in row.values():
                    values += f"'{val}', "
                
                values = values[: len(values) - 2]
                print(keys, values)
                cur.execute(f"INSERT INTO {table_name} ({keys}) VALUES ({values});")
            con.commit()
        cur.close()
        con.close()
    except Exception as e:
        print(e)
        return False
    return True


【讨论】:

  • 用给定的 JSON 数据测试。如果它没有回答你的问题,那么就没有理解你的问题。
  • 它的工作绝对是我试过的。你让我开心。谢谢@Sindbaad
猜你喜欢
  • 2019-09-14
  • 1970-01-01
  • 2021-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多