2015-01-15 12 views
0

이것은 내가 본 중에 가장 도움이되는 오류는 아니지만 Google에서 오류를 발생시키는 타이핑 오류 인 것처럼 보이지만 그 사실을 알 수 없습니다. 나는 그 명백한 것을 놓치고 있습니까?python mysql error <class '_mysql_exceptions.ProgrammingError'>

# 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

마지막 열의 유형이 정수형 인 경우'% s '주변에서'''을 제거해야합니다. –

+0

또한 데이터 형식이 'int'일 수있는 많은 열이 있습니다. 컬럼 이름에서 추측하고 있습니다. 이런 경우, 모든 컬럼에서'''를 제거해야합니다. –

답변

3

글쎄, error in the SQL or the table not being found과 같은 많은 것 때문일 수 있습니다. 문자열 형식화로 인해 예기치 않은 내용 (따옴표 나 세미콜론 또는 부적절하게 인용 된 값)을 SQL에 삽입 할 수 있기 때문에 SQL에 오류가 있는지 여부를 알 수 없습니다.

이 문제를 해결하는 한 가지 방법은 2-argument form of cur.execute을 사용하는 것이므로 해당 인수가 올바르게 인용됩니다. 이것은 (마지막 열이 숫자 유형의 경우 1'1' 인용 할 수 없습니다.) Prerak 솔라 밖으로 가리키는 인용 오류를 수정합니다

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 

을 그건 그렇고, 당신은 항상은 2 인자를 사용한다 양식을 수동으로 인용하는 대신 cur.execute 양식을 사용하면 SQL injection을 방지하는 데 도움이됩니다.