1

I'm having issues deleting rows from my database with python. I can hard code it like this:

del_student = "DELETE FROM students WHERE sid=34556"
cursor.execute(del_student)
cnx.commit()

but I'm trying to get sid from my entry box in my gui and this isn't working:

sid=SIDEnt.get()
del_student = "DELETE FROM students WHERE sid=%s"
cursor.execute(del_student,sid)
cnx.commit()

I'm rather new to python and I've tried looking through the posted questions already, thanks.

3
  • What is printed if you put print(repr(sid)) after the sid=SIDEnt.get() line ? Commented Nov 20, 2013 at 7:31
  • 2
    In addition to checking the value of sid, I believe that you need to use ? as a placeholder rather than %s. Commented Nov 20, 2013 at 7:36
  • If he's using MySQLdb the %s is the correct paramstyle. Commented Nov 20, 2013 at 7:50

2 Answers 2

2

sid needs to be in a tuple.

sid=SIDEnt.get()
del_student = "DELETE FROM students WHERE sid=%s"
cursor.execute(del_student,(sid,)) # put `sid` into a one-element tuple
cnx.commit()

The DB-API specifies, "Parameters may be provided as sequence or mapping..."

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

4 Comments

Here is the reference to the documentation that explains this: "Why the tuple? Because the DB API requires you to pass in any parameters as a sequence."
Thanks for adding that, Burhan. Indeed a one-element list is OK here too.
Amazing, would have never thought of adding an extra comma after sid, thanks so much.
@ifonlyirocked and also putting it in a box?
0

you haven't substituted the '%s' with any values; so your query is this:

'DELETE FROM students WHERE sid=%s'

it should be as follows:

sid=SIDEnt.get()
del_student = "DELETE FROM students WHERE sid=%s"%(sid,)
cursor.execute(del_student,sid)
cnx.commit()

1 Comment

You definitely do NOT want to use "%" in SQL, as it may allow an ''SQL injection''. Even if the variable 'sid' cannot be accessed by an attacker in this particular case, it is considered bad practice to use 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.