要从SQLite表中删除记录,你需要使用DELETE FROM语句。要删除特定的记录,你需要同时使用WHERE子句。
要更新特定的记录,你需要同时使用WHERE子句。
语法
以下是SQLite中DELETE查询的语法-
DELETE FROM table_name [WHERE Clause]
Python
例子
假设我们使用以下查询创建了一个名为CRICKETERS的表-
sqlite> CREATE TABLE CRICKETERS (
First_Name VARCHAR(255),
Last_Name VARCHAR(255),
Age int,
Place_Of_Birth VARCHAR(255),
Country VARCHAR(255)
);
sqlite>
Python
And if we have inserted 5 records in to it using INSERT statements as −
sqlite> insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India');
sqlite> insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica');
sqlite> insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');
sqlite> insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');
sqlite> insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India');
sqlite>
Python
以下声明删除了姓氏为 “Sangakkara “的板球运动员的记录。
sqlite> DELETE FROM CRICKETERS WHERE LAST_NAME = 'Sangakkara';
sqlite>
Python
如果你使用SELECT语句检索表的内容,你可以看到只有4条记录,因为我们已经删除了一条。
sqlite> SELECT * FROM CRICKETERS;
First_Name Last_Name Age Place_Of_B Country
---------- ---------- ---- ---------- -------------
Shikhar Dhawan 46 Delhi India
Jonathan Trott 39 CapeTown SouthAfrica
Virat Kohli 31 Delhi India
Rohit Sharma 33 Nagpur India
sqlite>
Python
如果你执行DELETE FROM语句而没有WHERE子句,那么指定表中的所有记录将被删除。
sqlite> DELETE FROM CRICKETERS;
sqlite>
Python
由于你已经删除了所有的记录,如果你试图检索CRICKETERS表的内容,使用SELECT语句你会得到一个空的结果集,如下图所示。
sqlite> SELECT * FROM CRICKETERS;
sqlite>
Python
使用python删除数据
将记录添加到SQLite数据库中的现有表中 −
- 导入sqlite3包。
-
使用 connect() 方法创建一个连接对象,将数据库的名称作为参数传给它。
-
cursor() 方法返回一个游标对象,你可以用它与SQLite3通信。通过在(上面创建的)Connection对象上调用cursor()对象来创建一个游标对象。
-
然后,在游标对象上调用execute()方法,将一个DELETE语句作为参数传递给它。
例子
下面的python例子从EMPLOYEE表中删除了年龄大于25岁的记录。
import sqlite3
#Connecting to sqlite
conn = sqlite3.connect('example.db')
#Creating a cursor object using the cursor() method
cursor = conn.cursor()
#Retrieving contents of the table
print("Contents of the table: ")
cursor.execute('''SELECT * from EMPLOYEE''')
print(cursor.fetchall())
#Deleting records
cursor.execute('''DELETE FROM EMPLOYEE WHERE AGE > 25''')
#Retrieving data after delete
print("Contents of the table after delete operation ")
cursor.execute("SELECT * from EMPLOYEE")
print(cursor.fetchall())
#Commit your changes in the database
conn.commit()
#Closing the connection
conn.close()
Python
输出
Contents of the table:
[('Ramya', 'Rama priya', 27, 'F', 9000.0),
('Vinay', 'Battacharya', 21, 'M', 6000.0),
('Sharukh', 'Sheik', 26, 'M', 8300.0),
('Sarmista', 'Sharma', 26, 'F', 10000.0),
('Tripthi', 'Mishra', 24, 'F', 6000.0)]
Contents of the table after delete operation
[('Vinay', 'Battacharya', 21, 'M', 6000.0),
('Tripthi', 'Mishra', 24, 'F', 6000.0)]
标签:sqlite,删除,Python,cursor,sqlite3,Copy,CRICKETERS,DELETE
From: https://www.cnblogs.com/weifeng1463/p/18332552