1

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

Mikicat
  • 73
  • 2
  • 9

3 Answers3

3

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.

krzys_h
  • 123
  • 8
1

I have found the problem, which was that instead of

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

I should have done

cur.execute("""INSERT INTO orders (name, size, type, is_done) 
 VALUES ("%s", "%s", "%s", "%s")""" 
% (name, size, type, is_done))
dreftymac
  • 31,404
  • 26
  • 119
  • 182
Mikicat
  • 73
  • 2
  • 9
0

if you don't input value for id. You have an error. Try this query.

cur.execute("insert into orders values(%s, %s, %s, %s, %s)", (None, name, size, type, is_done))

"%s" and "None" for id column. This query running my code. Note: Don't forget commit()