G_man
G_man

Reputation: 323

How can I delete a record using MySQL in Python?

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.

Upvotes: 0

Views: 112

Answers (3)

EyfI
EyfI

Reputation: 1005

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

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599956

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

Upvotes: 3

Flash Thunder
Flash Thunder

Reputation: 12045

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

Upvotes: 0

Related Questions