0

I am trying to insert values into a row of mysql database in a way that not be vulnerable to injection, but gives my syntax error. This is a piece of my code which causes the error:

cursor.execute("INSERT INTO api.mytable(id) VALUES (:id);", {"id": 1}) 

and error:

ERROR in connection: (1064, "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 ':id)' at line 1")

code you please tell me what's the wrong with my code?

6
  • Why not just pass the value directly instead of using dynamic parameters? like format the string and executing it. Commented Dec 14, 2019 at 9:48
  • 1
    first because I need to add external parameters to my query, second maybe it be helpful to avoid injection attacks Commented Dec 14, 2019 at 9:50
  • Did you try this? stackoverflow.com/a/37186271/4626254 Commented Dec 14, 2019 at 9:54
  • @Braiano use %(id)s instead of :id, i.e. cursor.execute("INSERT INTO api.mytable(id) VALUES (%(id)s);", {"id": 1}) Commented Dec 14, 2019 at 9:58
  • 1
    @SukumarRdjf that’s a dangerous suggestion, it’s vulnerable to SQL injection. Commented Dec 14, 2019 at 9:59

1 Answer 1

1

I am assuming id is given as some kind if input! Hence you can always check for the required format and allow only required ones! This is to avoid SQL injection!. Hence the natural formatting as shown below should do the job! And this is very basic level checking!

id_in = input("Here is the id taken " )  ## can be through any source . It is just an example 

if isinstance(id_in,int): ##Please mention the required format here I am assuming it as integer
    cursor.execute("INSERT INTO api.mytable(id) VALUES (%s);", (id_in))
else:
    ##do some  stuff here 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer, however since I have multiple inputs this solution is not quite fit. I just fixed it.
It should be [id_in] or (id_in,) (add a comma to make it a tuple).

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.