2

I am trying to insert HTML code into a field in a MySQL db.

I use the following code to do it

cur.execute("INSERT INTO `table1`(field1) VALUES("+ str(data) +")")

But I get the following error:

_mysql_exceptions.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 \'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 
Transitional//EN" "http://www.w3.or\' at line 3')

How can I solve this problem? Thanks in advance!

3
  • 4
    a) what does data look like, b) please please please don't use string concatenation to create SQL queries, use prepared statements or an ORM Commented Aug 15, 2012 at 15:41
  • 1
    Obligatory XKCD link: xkcd.com/327 Commented Aug 15, 2012 at 15:46
  • @DanielDiPaolo - I see it as less clear cut. Either you sanitise your SQL or you never ever let anyone ever use your code. Commented Aug 15, 2012 at 20:11

2 Answers 2

4

You should escape your string:

cur.execute("INSERT INTO `table1`(field1) VALUES('"+ conn.escape_string(str(data))+"')")

Where conn is your connection.

Sign up to request clarification or add additional context in comments.

4 Comments

I tried the following, however I got the error that conn. is not defined,so I changed it to mysqldb and it said that: code_mysql_exceptions.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 \'\\r\\n\\r\\n<!DOCTYPE HTML PUBLIC \\"-//W3C//DTD HTML 4.01 Transitional//EN\\" \\"http:\' at line 1') code
Can you post generated query? Also try to use this kind of brackets: '
The code works! Thanks! But I can seem to only select data, but it's not inserting. When I start a new .py file and use the same code to insert and it works. Any ideas?
Used: con.commit(). Works perfect now! Thanks for all the help!
1

Check your string - it looks like you are escaping single quotes but leaving double quotes un-escaped (and since you're enclosing with double-quotes, the string closes 'early').

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.