I have a database table called Students and I want to delete a record using SQL. Here is my code:
uid = int(input("Please enter students ID: "))
c.execute("DELETE FROM Students WHERE ID = (uid) ")
I want to input the ID variable (uid) into the c.execute
Thanks in advance.
icc97
13.1k9 gold badges84 silver badges99 bronze badges
3 Answers 3
You must not use string interpolation as recommended in the other answer; while in this specific case it might be OK, generally it is unsafe as it opens you up to SQL injection. Instead, use the support for parameters in the execute method:
uid = int(input("Please enter students ID: "))
c.execute("DELETE FROM Students WHERE ID = %s", (uid,))
answered Mar 4, 2017 at 11:37
Daniel Roseman
602k68 gold badges911 silver badges924 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Basically the syntax is:
"some string: %s, some int: %i, some double: %d" % (string_var,int_var,double_var)
so:
uid = int(input("Please enter students ID: "))
c.execute("DELETE FROM Students WHERE ID = %i" % (uid))
answered Mar 4, 2017 at 10:58
Flash Thunder
12.1k10 gold badges56 silver badges105 bronze badges
8 Comments
DeepSpace
This code is exposed to SQL injection. OP should use a parameterized query.
Flash Thunder
Not really... it is int... not vulnerable.
DeepSpace
And tomorrow OP will try to use a string in the same fashion.
Flash Thunder
Maybe, but this code is fine. Giving
-1 because I don't agree with you? Oh ok.Daniel Roseman
What? I can't understand how you can say that. This question is entirely about how to interpolate a variable into a database call. It is unquestionably unsafe to use string formatting to do that, which is why the database API provides a safe supported way to do it.
|
default
c.execute("DELETE FROM Students WHERE ID = {} ".format(uid))