Python MySQL 删除数据
要从MySQL表中删除记录,你需要使用 DELETE FROM 语句。要删除特定的记录,你需要同时使用WHERE子句。
语法
以下是MYSQL中DELETE查询的语法-
DELETE FROM table_name [WHERE Clause]
例子
假设我们在MySQL中创建了一个名为EMPLOYEES的表,作为 −
mysql> CREATE TABLE EMPLOYEE(
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT
);
Query OK, 0 rows affected (0.36 sec)
如果我们使用INSERT语句在其中插入4条记录,如:
mysql> INSERT INTO EMPLOYEE VALUES
('Krishna', 'Sharma', 19, 'M', 2000),
('Raj', 'Kandukuri', 20, 'M', 7000),
('Ramya', 'Ramapriya', 25, 'F', 5000),
('Mac', 'Mohan', 26, 'M', 2000);
以下MySQL语句删除了FIRST_NAME为 “Mac “的雇员记录。
mysql> DELETE FROM EMPLOYEE WHERE FIRST_NAME = 'Mac';
Query OK, 1 row affected (0.12 sec)
如果你检索该表的内容,你可以看到只有3条记录,因为我们已经删除了一条。
mysql> select * from EMPLOYEE;
+------------+-----------+------+------+--------+
| FIRST_NAME | LAST_NAME | AGE | SEX | INCOME |
+------------+-----------+------+------+--------+
| Krishna | Sharma | 20 | M | 2000 |
| Raj | Kandukuri | 21 | M | 7000 |
| Ramya | Ramapriya | 25 | F | 5000 |
+------------+-----------+------+------+--------+
3 rows in set (0.00 sec)
如果你执行DELETE语句而不使用WHERE子句,那么指定表中的所有记录都将被删除。
mysql> DELETE FROM EMPLOYEE;
Query OK, 3 rows affected (0.09 sec)
如果你检索表的内容,你会得到一个空集,如下图所示
mysql> select * from EMPLOYEE;
Empty set (0.00 sec)
使用python删除表的记录
当你想从数据库中删除一些记录时,就需要DELETE操作。
要删除一个表中的记录–
- 输入 mysql. connector包。
-
使用 mysql.connector.connect() 方法创建一个连接对象,将用户名、密码、主机(可选默认:localhost)和数据库(可选)作为参数传递给它。
-
通过在上面创建的连接对象上调用 cursor() 方法,创建一个游标对象。
-
然后,将 DELETE 语句作为参数传递给 execute() 方法,执行该语句。
例子
下面的程序删除了EMPLOYEE中年龄超过20岁的所有记录。
import mysql.connector
#establishing the connection
conn = mysql.connector.connect(
user='root', password='password', host='127.0.0.1', database='mydb')
#Creating a cursor object using the cursor() method
cursor = conn.cursor()
#Retrieving single row
print("Contents of the table: ")
cursor.execute("SELECT * from EMPLOYEE")
print(cursor.fetchall())
#Preparing the query to delete records
sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (25)
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
conn.commit()
except:
# Roll back in case there is any error
conn.rollback()
#Retrieving data
print("Contents of the table after delete operation ")
cursor.execute("SELECT * from EMPLOYEE")
print(cursor.fetchall())
#Closing the connection
conn.close()
输出
Contents of the table:
[('Krishna', 'Sharma', 22, 'M', 2000.0),
('Raj', 'Kandukuri', 23, 'M', 7000.0),
('Ramya', 'Ramapriya', 26, 'F', 5000.0),
('Mac', 'Mohan', 20, 'M', 2000.0),
('Ramya', 'Rama priya', 27, 'F', 9000.0)]
Contents of the table after delete operation:
[('Krishna', 'Sharma', 22, 'M', 2000.0),
('Raj', 'Kandukuri', 23, 'M', 7000.0),
('Mac', 'Mohan', 20, 'M', 2000.0)]