Usucha Bootsarakam Usucha Bootsarakam - 1 month ago 6
MySQL Question

Python not work DELETE mysql

I made program is input number and delete data in mysql. but run program error then report

sql1
Syntax Error

#!/usr/bin/python

import mysql.connector

conn = mysql.connector.connect(host="",user="",passwd="",db="")
cursor = conn.cursor()

print "---PROGRAM---"
num = int(input("InputNumber: ")

sql1 = "DELETE FROM dt WHERE user1 = '%i' " %(num)
try:
cursor.execute(sql1)
print "DELETE SUCECC"
conn.commit()
except:
conn.rollback()
print "ERROR DELETE"

conn.close()

Answer

num = int(input("InputNumber: ")) <- don't forguet to close it

I'm not sure about the %i, I always see using %d for Integer and %s to strings

But, you also have one problem into your query, SQL Injection

So to avoid this, try something like this

sql1 = "DELETE FROM dt WHERE user1 = ?"
                try:
                        cursor.execute(sql1, (num))
                        print "DELETE SUCECC"
                        conn.commit()
                except:
                        conn.rollback()
                        print "ERROR DELETE"

you can check about question mark here or here and understand why you should bind your values

Comments