2012-05-06 16 views
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"")" 

解決方法はありますか?

+0

作成しているテーブルは、挿入しているテーブルと同じではありません。 –

答えて

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

あなたINSERT文は、(SQL-注射がある)危険で何の入力をエスケープしません。 ファイルの行の1つに一重引用符(')が含まれていて、エスケープする必要があるため、エラーが発生しました。

+0

どのようにエスケープするのですか? – ThanaDaray

+1

別のクエリパラメータとして渡すとエスケープする必要はありません。 –

+0

そしてこの行には何がありますか?c.execute( "INSERT INTO Sentence_Qaem(Sentence)VALUES(%s)"、[row])? – dbf

関連する問題