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

4
  • check which query is really executed. stackoverflow.com/questions/7071166/… I think this link can help you. Commented Jan 25, 2017 at 18:01
  • Thanks, but I have seen that the command really is executed, so it's a dead end... Commented Jan 25, 2017 at 18:07
  • so, could you show excuted query? Commented Jan 25, 2017 at 18:10
  • @huhushow I have alredy found the problem, thanks for all :) Commented Jan 25, 2017 at 18:11

3 Answers 3

4

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.

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

Comments

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

Comments

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

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.