【问题标题】:Insert JSON array in mysql table using python使用python在mysql表中插入JSON数组
【发布时间】:2019-04-08 12:42:53
【问题描述】:

在 mysql 表“部分”中,我有 5 列(1 个 int、1 个文本和 3 个 json 数组)。 JSON 数组值以变量“s”、“l”和“t”的形式出现。我无法在表中插入值。我的代码如下:

mycursor.execute("""CREATE TABLE section (tid int, text text, spots json, spotl json, terms json)""")
s = json.dumps(["s1", "s2 s3"], ensure_ascii=False)
l = json.dumps(["L1", "L2"], ensure_ascii=False)
t = json.dumps(["t1", "t2"], ensure_ascii=False)
mycursor.execute("""INSERT INTO section (tid, text, spots, spotl, terms) VALUES ('101', 'pageview', ?, ?, ?)""", (s, l, t),)
print(mycursor.rowcount, " record inserted")
mycursor.execute("""SELECT * FROM section""")
x = mycursor.fetchall()
sp = x[0][2]
print(type(sp))

错误是:"mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement" for the line:" mycursor.execute("""INSERT INTO section (tid, text, points, spotl,术语)值('101','pageview',?,?,?)“”“,(s,l,t),)”。请帮忙。

【问题讨论】:

  • 您是否尝试过使用 %s 代替 ?
  • 您可能应该将您的 s、l 和 t JSON 组合到更高级别的 JSON 元素中并将其插入 MySQL 表。
  • @topher:是的,我试过了,它正在工作。但是,当使用“”“SELECT * FROM section”“”时,我无法将这些列(spots、spotl、terms)提取为 json 数组。

标签: python mysql json


【解决方案1】:

我已经编辑了我的答案,试试这个:

mycursor.execute("""INSERT INTO section (tid, text, spots, spotl, terms) VALUES ('101', 'pageview', %s, %s, %s)""", (s, l, t))

您无法提取列,因为通过查看您的代码,您尚未提交查询。在 mycursor.execute(Insert) 之后编写 commit 语句。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-08
    • 2019-08-29
    • 2018-03-02
    • 2011-05-14
    • 2020-05-08
    • 1970-01-01
    • 2015-12-29
    • 2015-05-10
    相关资源
    最近更新 更多