【发布时间】:2021-09-29 06:38:41
【问题描述】:
我不知道如何将包含列表的列插入 Postgresql 数据库。我知道这在理论上是可行的,因为存在像 BIGINT[] 这样的数据类型,而其他 SQL 变体则不存在。
这是我的代码:
import datetime
import json
import pandas as pd
import pymysql.cursors
from sqlalchemy import create_engine
mock_data = {}
mock_data['a'] = 'HELLO'
mock_data['b'] = {
'c' : {
'd' : True,
# NOTE: If you replace this with 'e' : '', instead of the list, it works fine.
'e' : []
},
'f' : 'TESTING'
}
df = pd.json_normalize(mock_data)
engine = create_engine("postgresql://postgres:ABCDEFG@localhost:5432/testing")
con = engine.connect()
table_name = 'testing-db'
try:
frame = df.to_sql(con=con, name=table_name, index=False, if_exists='replace')
display(frame)
except ValueError as vx:
print(vx)
except Exception as ex:
print(ex)
else:
print("Table %s created successfully."%table_name);
finally:
connection.close()
上面的代码失败了,因为 'e' : []。 Python/Pandas 不报告失败,但我看不到在 Postgres 中更新的表。但是,如果您将列表更改为空字符串,如下所示: 'e' : '' postgres 数据库已更新。我不知道如何使用 Pandas 将列表插入 Postgres 数据库。任何帮助将不胜感激。
【问题讨论】:
标签: python pandas postgresql