【发布时间】: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);
提前感谢您的帮助!
【问题讨论】:
-
如果
os是varchar我认为你应该用单引号 ((%s, %s, '%s')) 将其括起来。另请注意,True可能不起作用。 -
@dcg 谢谢,试过了,但仍然是同样的错误。
True实际上是一个布尔值,我已经用 %r 对它进行了测试,python 对象中没有任何双引号。如果没有 json,它会像这样工作。 -
不要插入 val,而是这样做:
cur.execute(sql, DEVICES)。 -
@mvp 刚试过,可惜还是一样的错误,我想我得把它从python转换成json。