在Python中从数据库中删除

时间:2016-05-04 19:45:08

标签: python mysql sql mysql-python

我有deleteuser.py我需要删除一个用户,这里是代码:

# Import modules for CGI handling
import MySQLdb
import cgi, cgitb

# Open database connection
db = MySQLdb.connect("localhost", "root", "", "moviedb" )

# prepare a cursor object using cursor() method
cursor = db.cursor()

# Create instance of FieldStorage 
form = cgi.FieldStorage() 

# Get data from fields
iduser = form.getvalue('iddelete')

# execute SQL query using execute() method.
try:
    cursor.execute("""DELETE FROM user WHERE
         ID = '%s'""",(iduser))
    # Commit your changes in the database
    db.commit()
except:
    db.rollback()

# disconnect from server
db.close()

print "Content-Type: text/plain;charset=utf-8"
print

我没有错误,但它不起作用。 数据库仍然是一样的。

谢谢

1 个答案:

答案 0 :(得分:1)

这是答案:

#!/Python27/python
# -*- coding: UTF-8 -*-


# Import modules for CGI handling
import MySQLdb
import cgi, cgitb

# Open database connection
db = MySQLdb.connect("localhost", "root", "", "moviedb" )

# prepare a cursor object using cursor() method
cursor = db.cursor()

# Create instance of FieldStorage 
form = cgi.FieldStorage() 

# Get data from fields
iduser = form.getvalue('iddelete')

# execute SQL query using execute() method.
query = "delete from user where id = '%s' " % iduser
cursor.execute(query)
    # Commit your changes in the database
db.commit()

# disconnect from server
db.close()

print "Content-Type: text/plain;charset=utf-8"
print