2016-05-31 81 views
0

有在Python 2.7使用以下MySQL查詢的問題用mysql連接器:問題與MySQL查詢和Python

這裏是我的代碼:

query = "INSERT INTO %s " % cfg['mysql.table'] 
query += "('hostname', 'metric', 'timestamp', 'average', 'peakhigh', 'peaklow', 'gsamp', 'zsamp', 'nsamp') " 
query += """VALUES (%s, %s, STR_TO_DATE(%s, '%Y%m%dT%h:%i:%s'), %s, %s, %s, %s, %s, %s)""" 

print query 
for record in DATA: 
    print record 
    cursor.execute(query, list(record)) 

而且我的輸出:

INSERT INTO perf ('hostname', 'metric', 'timestamp', 'average', 'peakhigh', 'peaklow', 'gsamp', 'zsamp', 'nsamp') VALUES (%s, %s, STR_TO_DATE(%s, '%Y%m%dT%h:%i:%s'), %s, %s, %s, %s, %s, %s) 
('somehost', 'cpu.utilization', '20160531T12:00:00', 9, 29, 0, 900, 0, 0) 

Traceback (most recent call last): 
    File "./perfquery.py", line 427, in <module> 
    mysql_dataload(cfg, CNX, DATA) 
    File "./perfquery.py", line 369, in mysql_dataload 
    cursor.execute(query, record) 
    File "/usr/local/python-2.76/lib/python2.7/site-packages/mysql/connector/cursor.py", line 504, in execute 
    stmt = RE_PY_PARAM.sub(psub, stmt) 
    File "/usr/local/python-2.76/lib/python2.7/site-packages/mysql/connector/cursor.py", line 70, in __call__ 
    "Not enough parameters for the SQL statement") 
mysql.connector.errors.ProgrammingError: Not enough parameters for the SQL statement 

我在猜str_to_date正在扔猴子扳手,但我已經玩了半打其他方法來做到這一點,並找不到有效的東西。

Thx尋求幫助。

+0

什麼是**記錄**?這是一個列表嗎? – arseniyandru

+0

其實我的不好,當時的記錄是一個元組。我現在將它轉換爲列表並仍然出現相同的錯誤。 (上面的代碼已更新) – BenH

回答

0

我猜INSERT INTO%s < - 未設置。您只設置記錄中的值,但不設置表名。

+0

我打印出查詢並且顯示正常。 – BenH

+0

你有沒有試圖逃跑,你的SQL調用是這樣的:STR_TO_DATE(%S,「%%ÿ%%米%%的dT %% H:%%我:%% S」) – arseniyandru

+1

我結束了剛剛返工日期字符串來從存儲設備中將其格式化爲日期時間格式所需的默認值,避免使用STR_TO_DATE,現在它正在工作。下次我會試着逃避你所說的。 – BenH