Edward Hammock Edward Hammock - 19 days ago 5
Python Question

Python not writing to MySQL (Type Error: format requires a mapping)

I am using a python programme to log data to a MySQL database. The database connection is made but I am getting the following error

Type Error: format requires a mapping
when the log is written.

The code of interest is as follows:

MySQL Table:

CREATE TABLE pidRun
(
pidKey INT auto_increment PRIMARY KEY,
pidSetPoint INT,
pidMeasure FLOAT,
pidError FLOAT,
integrator FLOAT,
derivator FLOAT
);


Python Code:

# 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)")


Then the code to insert the line at the requisite point is here:

data_pidRun = (pidControl.getPoint(), centSpeed, errSpeed, 0.0, 0.0)
cursor.execute(add_pidRun, data_pidRun)
dBase.commit()


pidControl.getPoint is a Integer

centSpeed is a float

errspeed is a float

Any direction is really appreciated.

Answer

As the error suggests, placeholders like %(pidSetPoint) require a mapping to be passed to cursor.execute(). Since you use a tuple, change the placeholders to "%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)

You don't need to specify the type of a value.