【问题标题】:Inserting dictionary of python in a single cell in mysql db在mysql db的单个单元格中插入python字典
【发布时间】:2014-10-04 14:42:01
【问题描述】:

我在 python 中有这本字典。我正在尝试将其插入 mysql db。所以我使用 json.dumps 将它转换为 json,但我仍然得到错误,即在字符串格式化期间并非所有参数都转换了。应该怎么做?

{'point': '+', 'time': '00:02', 'acceptedSubmissionId': 42, 'title': 'GNU C++'}

我的代码:cursor.execute("insert into tablename A value %s", json.dumps(user['scoreCard'][i]))

编辑:我将 json 放在方括号中,以创建一个元组,它可以工作。它是否正确?? cursor.execute("insert into contest_"+str(id)+" ("+str(unichr(i + 65))+") values (%s)", [json.dumps(user['scoreCard'][i])])

【问题讨论】:

  • A 是列名吗?即使这样,您也必须在列列表和值周围加上括号:`INSERT INTO tablename (A) VALUE (%s) ...
  • @VMai:我认为没有必要。反正我试过了还是不行
  • 你得到什么错误信息?
  • @VMai: TypeError: 在字符串格式化期间并非所有参数都转换了
  • 一个快速的谷歌搜索确实把我带到了stackoverflow.com/questions/21740359/…,也许它应该是cursor.execute("insert into tablename (A) value (%s)", [json.dumps(user['scoreCard'][i])])。我对 Python 并不坚定。

标签: python mysql json


【解决方案1】:

改用这个:

cursor.execute("insert into tablename A value {0}", json.dumps(user['scoreCard'][i]))

符号 %s 将很快被弃用。

【讨论】:

  • AFAIK,任何数据库都不支持这种语法 -- legacy.python.org/dev/peps/pep-0249/#paramstyle。也许您正在考虑使用%.format 进行常规字符串格式化......但即便如此,我也不知道有任何计划在短期内弃用%
猜你喜欢
  • 2017-08-03
  • 2016-05-30
  • 1970-01-01
  • 2015-03-18
  • 2022-01-24
  • 2018-05-22
  • 2013-02-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多