Search code examples
pythonmysqlpython-3.xpymysql

Insert Data with pymysql using inputs


I'm working on a DB and I'm having trouble when using pymysql to INSERT some values

cur.execute("""INSERT INTO orders (name, size, type, is_done) VALUES (%s, %s, %s, %s)""" 
% (name, size, type, is_done))

Where name, size and type are strings and is_done is a bool

It gives me the typical error 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, so I suppose the problem is a ', but how can I solve it?

Edit

I should also add that the name value is retrieved from a MySQL DB


Solution

  • The current accepted solution has a SQL injection vulnerability. You are not supposed to format the string with the % operator - just pass the tuple of arguments as a second argument, and the library will deal with the rest.

    cur.execute("INSERT INTO orders (name, size, type, is_done) VALUES (%s, %s, %s, %s)",
        (name, size, type, is_done))
    

    Also see this answer and pymysql documentation.