2017-08-30 61 views
1
#endcding=utf-8 
import MySQLdb 
conn = MySQLdb.connect{ 
    host='localhost' 
    port=3306, 
    user='root', 
    passwd='admin 
    db='db01', 
    charset='utf8 
    )    
cur = conn.cursor() 
count = cur.execute("select * from t_r_def_audit") 
results = cur.fetchmany(count) 
provcode = cur.execute("select * from t_r_params where 
param_tag='PROVINCE_CODE' and param_code not in(1,95,99)") 
provResults = cur.fetchmany(provcode) 
i = 0 
sql = "insert into ti_r_audit values({0},{1},{2},{3})" 
values = "[" 
for result in results: 
i = i+1 
prev = result[8] 
audit_id = result[0] 
if(prev == "1"): 
    prov = 31 
    for index in range(prov): 
     values =values + "("+str(i)+","+audit_id+",'"+provResults[index] 
    [0]+"',0)," 
     i = i+1 
elif prev=="0": 
    values =values + "("+str(i)+","+audit_id+",'"+provResults[31][0]+"',0)," 
values = values + "]" 
cur.executemany(sql,values) 
cur.close 
conn.commit() 
conn.close() 

手工縫製的SQL參數,用executableemany SQL實現,但是腳本的執行將被報告 後的誤差如下python2.7類型錯誤:不串轉換過程中的所有參數格式

λ python audit.py 
Traceback (most recent call last): 
File "audit.py", line 34, in <module> 
cur.executemany(sql,values) 
File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 255, in 
executemany 
self.errorhandler(self, TypeError, msg) 
File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 36, in 
defaulterrorhandler 
raise errorclass, errorvalue 
TypeError: not all arguments converted during string formatting 

自己寫的手動參數,沒有發現錯誤,說明腳本應該沒有問題,問題可能出在拼接SQL參數,但沒有發現哪裏有問題

+1

您發佈顯然是斷碼之前;看看語法高亮。請把它剪下來[mcve] – jonrsharpe

回答

1

ÿ我們的代碼是一個爛攤子,但行

sql = "insert into ti_r_audit values({0},{1},{2},{3})" 

需求,最終被稱爲沿

sql.format('first', 'second', 'third', 'forth') 

線的東西,從而確保您的列表values包含4個值,當你撥打:

cur.executemany(sql,values) 

否則你會看到錯誤:

TypeError: not all arguments converted during string formatting 

更新:

對於調試,你可以插入行:

print(sql.format(*values)) 

運行線

cur.executemany(sql,values) 
+0

對不起,代碼不完整。我的參數是拼接的一部分,值是參數的一部分,我打印出來,它確實是每行4個參數 – Cooper

+0

檢查我的更新並確保所有的SQL語句完好無缺 – AK47

+0

或正在給出,打印出來金額「insert into ti_r_audit values([,(,1 ,,)」 – Cooper

相關問題