从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);QueryOK,0rows affected(0.36sec)
如果我们使用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';QueryOK,1row affected(0.12sec)
如果您检索该表的内容,由于我们已删除一条记录,因此只能看到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)
如果执行不带WHERE子句的DELETE语句,则指定表中的所有记录将被删除。
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包。
通过将用户名,密码,主机(可选的默认值:localhost)和数据库(可选的)作为参数传递给它,使用mysql.connector.connect()方法创建连接对象。
通过在上面创建的连接对象上调用cursor()方法来创建游标对象。
然后,通过将DELETE语句作为参数传递给execute()方法来执行它。
例
以下程序从AGE大于20的EMPLOYEE中删除所有记录-
importmysql.connector#establishing the connectionconn=mysql.connector.connect(user='root',password='password',host='127.0.0.1',database='mydb')#Creating a cursor object using the cursor() methodcursor=conn.cursor()#Retrieving single rowprint("Contents of the table: ")cursor.execute("SELECT * from EMPLOYEE")print(cursor.fetchall())#Preparing the query to delete recordssql="DELETE FROM EMPLOYEE WHERE AGE > '%d'"%(25)try:# Execute the SQL commandcursor.execute(sql)# Commit your changes in the databaseconn.commit()except:# Roll back in case there is any errorconn.rollback()#Retrieving dataprint("Contents of the table after delete operation ")cursor.execute("SELECT * from EMPLOYEE")print(cursor.fetchall())#Closing the connectionconn.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)]