【问题标题】:Python objects to JSON to MySQLPython 对象到 JSON 到 MySQL
【发布时间】:2020-04-14 22:20:34
【问题描述】:

我在尝试将 json 插入 MySQL 数据库时遇到问题,该 json 是从带有 json.dumps 的 python 对象转换而来的。与数据库的连接正在使用另一个 python 文件。我已经尝试只插入值,这是有效的,但是对于 json 文件它不起作用。
我的 Python 文件:

import json
import dbConnection

cur = dbConnection.cursor
cnx = dbConnection.conn

DEVICES = {
        "id": "1",
        "isPoweredOn": "True",
    "os": "Linux"
}

j = json.dumps(DEVICES)
print(j)

sql = "INSERT INTO DEVICES (id, isPoweredOn, os) VALUES (%s, %s, %s)"


val = (json.dumps(DEVICES))


cur.execute(sql, val)
cnx.commit()
print(cur.rowcount, "record inserted.")

尝试执行时得到的错误代码:

"id": "1", "isPoweredOn": "True", "os": "Linux"}
Traceback (most recent call last):
  File "dbInit.py", line 22, in <module>
    cur.execute(sql, val)
  File "/home/silvan/.virtualenvs/pyproj1/lib/python3.8/site-packages/mysql/connector/cursor.py", line 551, in execute
    self._handle_result(self._connection.cmd_query(stmt))
  File "/home/silvan/.virtualenvs/pyproj1/lib/python3.8/site-packages/mysql/connector/connection.py", line 490, in cmd_query
    result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
  File "/home/silvan/.virtualenvs/pyproj1/lib/python3.8/site-packages/mysql/connector/connection.py", line 395, in _handle_result
    raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s, %s, %s)' at line 1

我的 CREATE TABLE 代码:

CREATE TABLE DEVICES(id INT AUTO_INCREMENT PRIMARY KEY NOT NULL, isPoweredOn BOOLEAN NOT NULL, os VARCHAR(50) NOT NULL);

提前感谢您的帮助!

【问题讨论】:

  • 如果 osvarchar 我认为你应该用单引号 ((%s, %s, '%s')) 将其括起来。另请注意,True 可能不起作用。
  • @dcg 谢谢,试过了,但仍然是同样的错误。 True 实际上是一个布尔值,我已经用 %r 对它进行了测试,python 对象中没有任何双引号。如果没有 json,它会像这样工作。
  • 不要插入 val,而是这样做:cur.execute(sql, DEVICES)
  • @mvp 刚试过,可惜还是一样的错误,我想我得把它从python转换成json。

标签: python mysql json


【解决方案1】:

您需要json.loads(j) 并将其分配给一个变量,然后您才能正确访问这些值。

试试:

import json
import dbConnection

cur = dbConnection.cursor
cnx = dbConnection.conn


DEVICES = {
        "id": "1",
        "isPoweredOn": False ,
        "os": "Linux"
}
j = json.dumps(DEVICES)
values = json.loads(j) 
'''
# Quick debugging 
print(j , type(j))
print(values , type(values))
print(values['isPoweredOn'])
'''

sql = "INSERT INTO DEVICES (id, isPoweredOn, os) VALUES (%s, %s, %s)"

val = ( '' , values['isPoweredOn'] , values['os'])

cur.execute(sql, val)
cnx.commit()
print(cur.rowcount, "record inserted.")

此外,由于您将 id 定义为 INT AUTO_INCREMENT PRIMARY KEY NOT NULL 它,因此您不能将 device idvalues['id'] 插入到 id column,您可以更改 DEVICES table 并创建一个名为 device_id 的新列用于存储device id,如果您确实需要存储values['id']

【讨论】:

  • 我已经尝试过了,但它不能正常工作,但上面的解决方案对我有用。无论如何,感谢您的意见。
【解决方案2】:

首先,将DEVICES 转换为dict,然后是格式。

sql = "INSERT INTO DEVICES (`id`, `isPoweredOn`, `os`) VALUES (%(id)s, %(isPoweredOn)s, %(os)s)"

然后执行它:

try:
    cur.execute(sql, DEVICES)
    cnx.commit()
except error:
    print(error)

干杯!!

【讨论】:

    猜你喜欢
    • 2018-06-15
    • 1970-01-01
    • 2011-01-20
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2012-03-22
    相关资源
    最近更新 更多