【问题标题】:How to insert a JSON object into SQL Server in Python automatically?如何在 Python 中自动将 JSON 对象插入 SQL Server?
【发布时间】:2020-11-29 08:09:49
【问题描述】:

我正在从 API 检索一些数据并将其插入本地 SQL Server 数据库以进行数据分析。

我想根据收到的Json对象结构创建表并填充到SQL Server中。有没有可以自动完成的 lib/framework python?

我正在使用 pyodbc 插入数据,如下所示。但是,我需要在 SQL Server 中手动创建每个表,并在 python 脚本上逐个字段记下以插入数据。

response = requests.get(url, headers=headers , auth=auth )
parseResponse = json.loads(response.text) 

conn = pyodbc.connect(constant.DW_CONNECTION)
cursor = conn.cursor()

for record in parseResponse:
    print( "Insert Into LeadSource (RequestGuid, [Key], Description, LocationNumber, Inactive, ShowOnline) values " + json.dumps(convert(record)) )
    cursor.execute("Insert Into LeadSource (RequestGuid, [Key], Description, LocationNumber, Inactive, ShowOnline) values (?, ?, ?, ?, ?, ?)", ( record['RequestGuid'], record['Key'], record['Description'], record['LocationNumber'], record['Inactive'], record['ShowOnline'] ) )
conn.commit()
conn.close()

【问题讨论】:

  • 你能不能用pandas的@​​987654321@把JSON拉到DataTable然后用to_sql上传到数据库?
  • 我会将 Pandas 保留为数据科学工具,而不是数据迁移工具。此外,我不会有一个 Python 脚本即时构建表。像 MSSQL 这样的企业数据库应该是预先知道所有表的计划项目。另外,如果您需要一个脚本来创建 50+/100+ 个表,这可能是一个有问题的数据库设计。
  • 深思熟虑的@Parfait。此 MSSQL 是一个临时 DW,当我获准迁移到云时,将使用 Azure 数据工厂。

标签: python sql-server etl pyodbc


【解决方案1】:

感谢上帝,

这就是我想要的。最终代码:


response = requests.get(url, headers=headers , auth=auth )
parseResponse = json.loads(response.text) 

# Converting the JSON text to Pandas Dataframe
df = pd.read_json(response.text)

# Create an in-memory SQLite database.
engine = sal.create_engine(constant.DW_STR_CONNECTION)
conn = engine.connect()

# Create and insert the entity 'leads' into DW MSSQL
df.to_sql('LeadSource', con=engine, if_exists='replace', index_label='id')

DW_STR_CONNECTION 应该是这样的:

服务器 = 主机名\\SqlInstance

DW_STR_CONNECTION = 'mssql+pyodbc://' + 用户名 + ':' + 密码 + '@' + 服务器 + '/'+database+'?driver=SQL Server?Trusted_Connection=yes'

【讨论】:

    猜你喜欢
    • 2018-06-03
    • 2017-06-25
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-27
    • 1970-01-01
    • 2016-01-26
    相关资源
    最近更新 更多