2016-04-27 50 views
0

我正在使用python程序將數據記錄到MySQL數據庫。數據庫連接已建立,但在寫入日誌時出現以下錯誤Type Error: format requires a mappingPython不寫入MySQL(類型錯誤:格式需要映射)

感興趣的代碼如下:

MySQL表:

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是浮法

任何方向是真正理解。

回答

0

由於錯誤提示,像%(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) 

你並不需要指定值的類型。

+0

完美。我需要確定爲什麼我應該在列表中使用元組! –

相關問題