python mysql错误<class'_mysql_exceptions.programmingerror'=“”> </class>

时间:2015-01-15 12:54:19

标签: python mysql sql python-2.7

这不是我见过的最有用的错误,但是从谷歌这似乎是一个输入错误,导致错误,但我不能弄明白。我错过了明显的吗?

# Prepare SQL query to INSERT a record into the database.
sql = "INSERT INTO spin_hdd(error_count, raw_read_error, spin_up_time, allo_sec, seek_error, spin_retry, gsense_error, power_on_hours, pending_sector, load_retry, spin_up_time, max_temp, sector_count, short_test_time, long_test_time, model, serial, firmware, ip, running) \
       VALUES ('%s','%s','%s','%s','%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')" % \
       (error_count, raw_read_error, spin_up_time, allo_sec, seek_error, spin_retry, gsense, power_on, pend_sec, load_retry, spin_up_time, max_temp, sector_count, testShortTime, testLongTime, model_count, serial, firmware, ip, 1)
try:
   # Execute the SQL command
   cur.execute(sql)
   # Commit your changes in the database
   con.commit()
   # get last inserted id
   id = cur.lastrowid
except:
   # Rollback in case there is any error
   con.rollback()
   e = sys.exc_info()[0]
   print e

1 个答案:

答案 0 :(得分:3)

嗯,这可能是由于许多事情,例如error in the SQL or the table not being found。我们不可能判断SQL中是否存在错误,因为字符串格式化可能会在SQL中插入一些意外的内容(如引号或分号或其他不正确引用的值)。

可能解决问题的一件事是使用2-argument form of cur.execute,它将为您正确引用参数。这将更正Prera​​k Sola指出的引用错误(1如果最后一列是数字类型,则不应引用'1'。)

sql = """INSERT INTO spin_hdd(
            error_count, raw_read_error, spin_up_time, allo_sec, seek_error, 
            spin_retry, gsense_error, power_on_hours, pending_sector, load_retry, 
            spin_up_time, max_temp, sector_count, short_test_time,
            long_test_time, model, serial, firmware, ip, running) 
         VALUES ({})""".format(', '.join(['%s']*20))

args = (error_count, raw_read_error, spin_up_time, allo_sec, seek_error,
        spin_retry, gsense, power_on, pend_sec, load_retry, spin_up_time,
        max_temp, sector_count, testShortTime, testLongTime, model_count,
        serial, firmware, ip, 1)
try:
   # Execute the SQL command
   cur.execute(sql, args)
   # Commit your changes in the database
   con.commit()
   # get last inserted id
   id = cur.lastrowid
except:
   # Rollback in case there is any error
   con.rollback()
   e = sys.exc_info()[0]
   print e

顺便说一句,你应该总是使用cur.execute的2参数形式,而不是自己手动引用参数,因为这有助于防止SQL injection