2013-03-24 67 views
1

問題的Python mysql的問題與%s爲表

爲什麼%s轉義序列不是在我與MySQL包Python腳本工作?

背景和代碼

我有以下行的一個問題:

cursor.execute("""INSERT INTO `%s` (Date, Counter_in, Counter_out, Interface_name) VALUES (CURRENT_TIMESTAMP, %s, %s, %s)""", (Equipment, In_Octets, Out_Octets, interface)) 

我收到以下錯誤信息:

Traceback (most recent call last): 
    File "SNMP_Query.py", line 41, in <module> 
    cursor.execute("""INSERT INTO `%s` (Date, Counter_in, Counter_out, Interface_name) VALUES (CURRENT_TIMESTAMP, %s, %s, %s)""", (Equipment, In_Octets, Out_Octets, interface)) 
    File "/usr/lib/pymodules/python2.6/MySQLdb/cursors.py", line 166, in execute 
    self.errorhandler(self, exc, value) 
    File "/usr/lib/pymodules/python2.6/MySQLdb/connections.py", line 35, in defaulterrorhandler 
    raise errorclass, errorvalue 
_mysql_exceptions.ProgrammingError: (1146, "Table 'Sipartech.'itx6-f10-1'' doesn't exist") 

我有雙重檢查和表它確實存在。

+0

您是否嘗試從查詢中移除引號? – alecxe 2013-03-24 19:10:41

回答

1

一個錯誤,我可以在插入查詢注意的是,你是寫Date列名不(`)符號,其中日期爲MySQL date type:關鍵字。因此,在您的查詢: -

cursor.execute("""INSERT INTO `%s` (Date, Counter_in, 
            ^

應該

cursor.execute("""INSERT INTO `%s` (`Date`, `Counter_in`,      
            ^added (`) 

其次,我不明白爲什麼MySQL的1146錯誤?這發生在數據庫文件丟失時。
因爲我可以注意到%s正在工作,您可以從代碼中找到來自Equipment的Python變量的數據庫名稱。

可是爲什麼你越來越:

'Sipartech.'itx6-f10-1'' 
      ^  ^extra ' 

的,當然這不可能是一個數據庫名稱,可能是MySQL錯誤的原因:1146,你應該得到:

'Sipartech.itx6-f10-1' 

檢查代碼和查詢。

另外,如果您對%s有疑問,那麼您可以使用string.formate()函數代替%s。像:

 """ 
     INSERT INTO {0} (`Date`, 
         `Counter_in`, 
         `Counter_out`, 
         `Interface_name`) 
     VALUES (CURRENT_TIMESTAMP, {1}, {2}, {3}) 
     """.formate(Equipment, In_Octets, Out_Octets, interface)) 

另外,請記住,如果In_Octets, Out_Octets, interface整數然後把'各地查詢字符串中每個括號{}