使用 pymysql 将 Json 文件连接到 MySQL 数据库时出错
Posted
技术标签:
【中文标题】使用 pymysql 将 Json 文件连接到 MySQL 数据库时出错【英文标题】:Error connecting Json file to MySQL database using pymysql 【发布时间】:2021-10-11 12:16:18 【问题描述】:import pymysql
import json
json_data = open("data_chart.json").read()
json_obj = json.loads(json_data)
connection = pymysql.connect(host='', user='=',
password='=', database='=')
cursor = connection.cursor()
for item in json_obj:
Current_Fridge_Temp = item.get("Current Fridge Temperature")
Target_Fridge_Temp = item.get("Target Fridge Temperature")
Current_Freezer_Temp = item.get("Current Freezer Temperature")
Target_Freezer_Temp = item.get("Target Freezer Temperature")
E_Use = item.get("Energy Use")
Fridge_Last_On = item.get("Fridge Last On Time")
Fridge_Last_Off = item.get("Fridge Last Off Time")
Freezer_Last_On = item.get("Freezer Last On Time")
Freezer_Last_Off = item.get("Freezer Last Off Time")
cursor.execute("insert into refrigerator_id(Current Fridge Temperature, Target Fridge Temperature, "
"Current Freezer Temperature, Target Freezer Temperature, Energy Use, Fridge Last On Time, "
"Fridge Last Off Time, Freezer Last On Time, Freezer Last Off Time) "
"VALUES(%d,%d,%d,%d,%d,%d,%d,%d,%d)", (Current_Fridge_Temp, Target_Fridge_Temp, Current_Freezer_Temp,
Target_Freezer_Temp, E_Use, Fridge_Last_On, Fridge_Last_Off,
Freezer_Last_On, Freezer_Last_Off))
connection.commit()
connection.close()
获取这些回溯错误:
Traceback (most recent call last):
File "/Users/ConnectionTest.py", line 24, in <module>
cursor.execute("insert into refrigerator_id(Current Fridge Temperature, Target Fridge Temperature, "
File "/Users/venv/lib/python3.8/site-packages/pymysql/cursors.py", line 146, in execute
query = self.mogrify(query, args)
File "/Users/venv/lib/python3.8/site-packages/pymysql/cursors.py", line 125, in mogrify
query = query % self._escape_args(args, conn)
TypeError: %d format: a number is required, not str
我尝试将 VALUES 更改为 %s,但没有成功。
【问题讨论】:
“没有”将其更改为%s
究竟是如何工作的?
这没有帮助,给我们完整的错误信息。 SQL 语句的正确占位符是 %s
.
@sam:这不是完整的错误消息,缺少信息部分。请将程序的完整输出(包括完整的错误消息,格式正确)复制粘贴到问题中。
@sam:请将整个错误消息复制粘贴到问题中。不要截断它!
将所有项目从 json 转换为 int,因为 json 只返回字符串
【参考方案1】:
Jsons 元素都是字符串,所以你需要在运行查询之前将它们转换成整数
Current_Fridge_Temp = int(item.get("Current Fridge Temperature")))
Target_Fridge_Temp = int(item.get("Target Fridge Temperature"))
Current_Freezer_Temp = int(item.get("Current Freezer Temperature"))
Target_Freezer_Temp = int(item.get("Target Freezer Temperature"))
E_Use = int(item.get("Energy Use"))
Fridge_Last_On = item.get("Fridge Last On Time")
Fridge_Last_Off = item.get("Fridge Last Off Time")
Freezer_Last_On = item.get("Freezer Last On Time")
Freezer_Last_Off = item.get("Freezer Last Off Time")
【讨论】:
谢谢,这可以工作,但在第 19 行 Traceback 上出现错误(最近一次调用最后一次):文件“/Users/PycharmProjects/cConnectionTest.py”,第 19 行,在以上是关于使用 pymysql 将 Json 文件连接到 MySQL 数据库时出错的主要内容,如果未能解决你的问题,请参考以下文章
SQLAlchemy 和 PyMySQL 在连接到 AWS RDS 后拒绝连接到“localhost”
无法在 Windows 机器上使用 sqlalchemy 连接到本地 mysql 数据库