Reputation: 1693
In test.txt, I have 2 lines of sentences.
The heart was made to be broken.
There is no surprise more magical than the surprise of being loved.
In codes:
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()
I tried to inset into database but I got error.
"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"")"
Any possible way for solving it?
Upvotes: 0
Views: 699
Reputation: 8231
c.execute("INSERT INTO Sentence_Qaem (Sentence) VALUES (%s)", row)
Your INSERT
statement doesn't escape input what is dangerous (there are SQL-injections).
You got error because one of row in file contains single quote ('
) tat should be escaped as well.
Upvotes: 4