2016-02-02 122 views
0

遇到了使用動態列表將值插入到mysql表中的問題。我一直有一個問題,指向一個表而不是一個值的引號。使用python將特殊字符的值插入到mysql表中時出錯

下面是代碼:

lst = ['Pid', 'Base', 'Size', 'LoadCount', 'Path','Casename'] 
lst2 =['888', '1213726720', '61440', '65535', '\\SystemRoot\\System32\\smss.exe', 'wean'] 

table_name ="test" 
insert_intotable = "INSERT INTO " + table_name + "(" + ",".join(lst) + ") VALUES (" + ",".join(lst2) + ")" 
print insert_intotable 
c.execute(insert_intotable) 
conn.commit() 
c.close() 
conn.close() 

這會導致以下錯誤:

> Traceback (most recent call last): File "pp.py", line 53, in 
> <module> 
>  c.execute(insert_intotable) File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 174, in 
> execute 
>  self.errorhandler(self, exc, value) File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in 
> defaulterrorhandler 
>  raise errorclass, errorvalue 
> _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server 
> version for the right syntax to use near 
> '\\SystemRoot\\System32\\smss.exe,test)' at line 1") 

是什麼原因造成的語法問題?

+0

你必須使用由MySQL適配器提供的字符串格式化的記載:https://dev.mysql.com/doc/connector-python/en/connector- python-api-mysqlcursor-execute.html –

回答

0

使用 '單引號' 插入時串值

UPD:

更改第二行此

lst2 =['888', '1213726720', '61440', '65535', '\'\\SystemRoot\\System32\\smss.exe\'', '\'wean\''] 

因爲,這是錯誤的SQL查詢:

INSERT INTO test (Path) VALUES(\SystemRoot\System32\smss.exe) 

而你的代碼生成這樣的查詢。

你應該引用VARCHAR值:

INSERT INTO test (Path) VALUES('\SystemRoot\System32\smss.exe') 
+0

我已經將它們全部轉換爲使用str()的字符串。我應該善於表達你的觀點。 –

+0

對這兩個添加'\'有什麼意義。我問,因爲我想讓他們自動化,因爲我將有不同的值列表後面有不同的列表。 –

+0

非常感謝。 –