0

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.

3
  • 1
    I guess you are looking for: c.execute("DELETE FROM Students WHERE ID = {} ".format(uid)) Commented Mar 4, 2017 at 10:57
  • @JustRufus Keep in mind that this example is exposed to SQL injection. Commented Mar 4, 2017 at 11:19
  • It is not, as it's int... you can't inject any code with int. Commented Mar 4, 2017 at 11:20

3 Answers 3

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,))
Sign up to request clarification or add additional context in comments.

Comments

1

What Daniel Roseman said should be the correct answer.

You can insert the ID as a parameter for the .execute method. There is an answer about this here

Comments

0

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

8 Comments

This code is exposed to SQL injection. OP should use a parameterized query.
Not really... it is int... not vulnerable.
And tomorrow OP will try to use a string in the same fashion.
Maybe, but this code is fine. Giving -1 because I don't agree with you? Oh ok.
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.
|

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.