2012-05-06 279 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