0

在 test.txt 中,我有 2 行句子。

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"")"   

有什么可能的解决方法吗?

4

1 回答 1

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

您的INSERT语句不会逃避输入什么是危险的(有 SQL 注入)。您收到错误,因为文件中的一行包含单引号 ( ') tat 也应该被转义。

于 2012-05-06T17:28:24.377 回答