python2.7 TypeError:在字符串格式化过程中并非所有参数都被转换

时间:2017-08-30 12:51:52

标签: python mysql python-2.7 python-2.x

#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的参数,用executeemany实现sql,但是在执行脚本后会报告 错误如下

λ 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 个答案:

答案 0 :(得分: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)