SQLAlChemy(mental copg2.ProgrammingError)不能适配类型。 [英] SQLAlchemy (psycopg2.ProgrammingError) can't adapt type 'dict'

查看:43
本文介绍了SQLAlChemy(mental copg2.ProgrammingError)不能适配类型。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Web上找不到我的问题的解决方案。 我正在尝试使用SQLAlChemy将此 pandas DF插入到PostgreSQL表

  • pandas 0.24.2
  • sqlalChemical 1.3.3
  • python 3.7

我的代码相关部分如下:

engine = create_engine('postgresql://user:pass@host:5432/db')

file = open('GameRoundMessageBlackjackSample.json', 'r', encoding='utf-8')
json_dict = json.load(file)
df = json_normalize(json_dict, record_path='cards', meta=['bet', 'dealerId', 'dealerName', 'gameOutcome', 'gameRoundDuration', 'gameRoundId', 'gameType', 'tableId', 'win'])
df = df[['win', 'betAmount', 'bets']]

df.to_sql('test_netent_data', engine, if_exists='append')

当我尝试将该表加载到SQL中时,没有‘BETTS’列,一切都按预期进行。但是当我包含它时,我得到以下错误:

sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) can't adapt 
type 'dict'
[SQL: INSERT INTO test_netent_data (index, win, "betAmount", bets) VALUES (%(index)s, %(win)s, %(betAmount)s, %(bets)s)]
[parameters: ({'index': 0, 'win': '2000.00', 'betAmount': '1212112', 'bets': [{'name': '1', 'amount': '1212112'}]}, {'index': 1, 'win': '2000.00', 'betAmount': '1212000', 'bets': [{'name': '1', 'amount': '1212000'}]}, {'index': 2, 'win': '2000.00', 'betAmount': '1212112', 'bets': [{'name': '1', 'amount': '1212112'}]}, {'index': 3, 'win': '2000.00', 'betAmount': '1212000', 'bets': [{'name': '1', 'amount': '1212000'}]}, {'index': 4, 'win': '2000.00', 'betAmount': '1212112', 'bets': [{'name': '1', 'amount': '1212112'}]}, {'index': 5, 'win': '2000.00', 'betAmount': '1212000', 'bets': [{'name': '1', 'amount': '1212000'}]}, {'index': 6, 'win': '2000.00', 'betAmount': '1212112', 'bets': [{'name': '1', 'amount': '1212112'}]}, {'index': 7, 'win': '2000.00', 'betAmount': '1212000', 'bets': [{'name': '1', 'amount': '1212000'}]})]
(Background on this error at: http://sqlalche.me/e/f405)
我检查了此列的类型,但它(Object类型)与其他列没有什么不同。我还试图将其转换为字符串,但得到了一堆其他错误。 我相信应该有一个我想不通的简单解决方案。

推荐答案

对我来说,更好的方法是将此列表字典解析为单独的列。但是,如果您希望将列Botts添加到SQL表中,则需要对其进行转换。您写了这是Object,但它是用字典列出的。下面是如何将其转换为字符串的代码:

df['bets'] = list(map(lambda x: json.dumps(x), df['bets']))

这篇关于SQLAlChemy(mental copg2.ProgrammingError)不能适配类型。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆