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インジェクションがあります)。ファイル内の行の 1 つに一重引用符 ( ') が含まれているため、エラーが発生しました。tat もエスケープする必要があります。

于 2012-05-06T17:28:24.377 に答える