Python not writing to MySQL (Type Error: format requires a mapping)
Python not writing to MySQL (Type Error: format requires a mapping)
我正在使用 python 程序将数据记录到 MySQL 数据库。已建立数据库连接,但在写入日志时出现以下错误 Type Error: format requires a mapping
。
感兴趣的代码如下:
MySQL Table:
CREATE TABLE pidRun
(
pidKey INT auto_increment PRIMARY KEY,
pidSetPoint INT,
pidMeasure FLOAT,
pidError FLOAT,
integrator FLOAT,
derivator FLOAT
);
Python代码:
# Insert a new line to table pidRun
add_pidRun = ("INSERT INTO pidRun "
"(pidSetPoint, pidMeasure, pidError, integrator, derivator)"
"VALUES (%(pidSetPoint)i, %(pidMeasure)f, %(pidError)f, %(integrator)f, %(derivator)f)")
那么在必要的点插入行的代码在这里:
data_pidRun = (pidControl.getPoint(), centSpeed, errSpeed, 0.0, 0.0)
cursor.execute(add_pidRun, data_pidRun)
dBase.commit()
pidControl.getPoint 是一个整数
centSpeed 是一个浮点数
errspeed 是一个浮点数
非常感谢任何方向。
如错误所示,像 %(pidSetPoint)
这样的占位符需要将映射传递给 cursor.execute()
。由于您使用元组,因此将占位符更改为 "%s"
:
add_pidRun = ("INSERT INTO pidRun "
"(pidSetPoint, pidMeasure, pidError, integrator, derivator)"
"VALUES (%s, %s, %s, %s, %s")
data_pidRun = (pidControl.getPoint(), centSpeed, errSpeed, 0.0, 0.0)
cursor.execute(add_pidRun, data_pidRun)
您不需要指定值的类型。
我正在使用 python 程序将数据记录到 MySQL 数据库。已建立数据库连接,但在写入日志时出现以下错误 Type Error: format requires a mapping
。
感兴趣的代码如下:
MySQL Table:
CREATE TABLE pidRun
(
pidKey INT auto_increment PRIMARY KEY,
pidSetPoint INT,
pidMeasure FLOAT,
pidError FLOAT,
integrator FLOAT,
derivator FLOAT
);
Python代码:
# Insert a new line to table pidRun
add_pidRun = ("INSERT INTO pidRun "
"(pidSetPoint, pidMeasure, pidError, integrator, derivator)"
"VALUES (%(pidSetPoint)i, %(pidMeasure)f, %(pidError)f, %(integrator)f, %(derivator)f)")
那么在必要的点插入行的代码在这里:
data_pidRun = (pidControl.getPoint(), centSpeed, errSpeed, 0.0, 0.0)
cursor.execute(add_pidRun, data_pidRun)
dBase.commit()
pidControl.getPoint 是一个整数
centSpeed 是一个浮点数
errspeed 是一个浮点数
非常感谢任何方向。
如错误所示,像 %(pidSetPoint)
这样的占位符需要将映射传递给 cursor.execute()
。由于您使用元组,因此将占位符更改为 "%s"
:
add_pidRun = ("INSERT INTO pidRun "
"(pidSetPoint, pidMeasure, pidError, integrator, derivator)"
"VALUES (%s, %s, %s, %s, %s")
data_pidRun = (pidControl.getPoint(), centSpeed, errSpeed, 0.0, 0.0)
cursor.execute(add_pidRun, data_pidRun)
您不需要指定值的类型。