Mikicat
Mikicat

Reputation: 73

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

Upvotes: 1

Views: 9154

Answers (3)

krzys_h
krzys_h

Reputation: 153

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.

Upvotes: 4

yunusemredemirbas
yunusemredemirbas

Reputation: 152

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()

Upvotes: 0

Mikicat
Mikicat

Reputation: 73

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))

Upvotes: 1

Related Questions