2012-05-06 283 views
0

在test.txt中,我有兩行句子。如何將數據插入數據庫?

The heart was made to be broken. 
There is no surprise more magical than the surprise of being loved. 

在代碼:

import MySQLdb, csv, sys 
db = MySQLdb.connect("host","username","password","databasename") 
c = db.cursor() 
sql_drop = "DROP TABLE IF EXISTS Sentence" 
c.execute(sql_drop) 
sql = """CREATE TABLE Sentence(
    No INT, 
    Sentence CHAR(255) NOT NULL)""" 
csv_data=csv.reader(file("/test.txt")) 
for row in csv_data: 
    print row 
sql_insert = "INSERT INTO Sentence (Sentence) VALUES ('%s')" % row 
c.execute(sql_insert) 
db.close() 

我試圖嵌入到數據庫中,但我得到了錯誤。

"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 'There is no 
surprise more magical than the surprise of being loved.']')' at line 1"")" 

任何可能的解決方法嗎?

+0

您正在創建的表格與您插入的表格不一樣... –

回答

4
c.execute("INSERT INTO Sentence_Qaem (Sentence) VALUES (%s)", row) 

您的INSERT語句不會轉義輸入什麼是危險的(有SQL注入)。 你得到錯誤,因爲文件中的一行包含單引號(')tat也應該被轉義。

+0

那麼如何逃避它呢? – ThanaDaray

+1

如果您將它作爲單獨的查詢參數傳遞,則不需要轉義。 –

+0

你對這行有什麼建議:c.execute(「INSERT INTO Sentence_Qaem(Sentence)VALUES(%s)」,[row])? – dbf