Search code examples
mysqlpython-3.xpymysql

Invalid syntax when using PyMySQL


I'm learning using Python with MySQL. The same query works differently between Mysql and PyMySQL. For example: In MySQL console I have a table named "pages"

INSERT INTO pages (title,content) VALUES ("test title","test content")

And this works. In Python, I import PyMySQL, I create a connection and then type cursor = "cur". When I run:

cur.execute("INSERT INTO pages (title,content) VALUES ("test title","test content")")

.. it raises an error : invalid syntax. But when I try this with the place holder:

cur.execute("insert into pages (title,content) values (%s,%s)",("test title","test content"))

Then it works! So I was confused why same query work in MySQL but not in python,and does It means I should always use place holder when using PyMySQL?

Thanks


Solution

  • First of all, the last version (the parameterized query) should be the most preferred one since you don't need to put the quotes around the placeholders at all letting the database driver figure out the type conversion and the quotes automatically. And, this way you are safe from SQL injection attacks.

    Now, to answering your question. If you want to use double quotes inside double quotes, you need to escape them:

    cur.execute("INSERT INTO pages (title,content) VALUES (\"test title\", \"test content\")")
    

    Or, use single quotes outside and double quotes inside:

    cur.execute('INSERT INTO pages (title,content) VALUES ("test title", "test content")')