15条SQLite3语句

本文详细介绍了如何使用SQLite创建数据库、表,插入记录,查看记录,重命名表,添加列,创建唯一索引,创建触发器,创建视图,保存点、回滚和提交操作,以及日期函数和操作符的基本使用。

转自:http://www.thegeekstuff.com/2012/09/sqlite-command-examples/

 

SQLite3 is very lightweight SQL database which focuses on simplicity more than anything else. This is a self-contained serverless database engine, which is very simple to install and use.

While most of the commands in the SQLite are similar to SQL commands of other datbases like MySQL and ORACLE, there are some SQLite SQL commands that are different.

This article explains all the basic SQL commands that you need to know to use the SQLite database effectively.

If you don’t have sqlite installed, execute “yum install sqlite” to install it. You can also install SQLite database from source to get the latest version.

1. Create a SQLite Database (and a Table)

First, let us understand how create a SQLite database with couple of tables, populate some data, and view those records.

The following example creates a database called employee.db. This also creates an employee table with 3 columns (id, name and title), and a department table in the company.db database. We’ve purposefully missed the deptid column in the employee table. We’ll see how to add that later.

# sqlite3 company.db 
sqlite> create table employee(empid integer,name varchar(20),title varchar(10)); 
sqlite> create table department(deptid integer,name varchar(20),location varchar(10)); 
sqlite> .quit

Note: To exit from the SQLite commandline “sqlite>” prompt, type “.quit” as shown above.

A SQLite database is nothing but a file that gets created under your current directory as shown below.

# ls -l company.db -rw-r--r--. 1 root root 3072 Sep 19 11:21 company.db

2. Insert Records

The following example populates both employee and department table with some sample records.

You can execute all the insert statements from the sqlite command line, or you can add those commands into a file and execute the file as shown below.

First, create a insert-data.sql file as shown below.

# vi insert-data.sql 
insert into employee values(101,'John Smith','CEO'); 
insert into employee values(102,'Raj Reddy','Sysadmin'); 
insert into employee values(103,'Jason Bourne','Developer');
insert into employee values(104,'Jane Smith','Sale Manager'); 
insert into employee values(105,'Rita Patel','DBA');  
insert into department values(1,'Sales','Los Angeles'); 
insert into department values(2,'Technology','San Jose'); 
insert into department values(3,'Marketing','Los Angeles');

The following will execute all the commands from the insert-data.sql in the company.db database

# sqlite3 company.db < insert-data.sql

3. View Records

Once you’ve inserted the records, view it using select command as shown below.

# sqlite3 company.db 
sqlite> select * from employee; 
101|John Smith|CEO 
102|Raj Reddy|Sysadmin 
103|Jason Bourne|Developer 
104|Jane Smith|Sale Manager 
105|Rita Patel|DBA  
sqlite> select * from department; 
1|Sales|Los Angeles 
2|Technology|San Jose 
3|Marketing|Los Angeles

4. Rename a Table

The following example renames department table to dept using the alter table command.

sqlite> alter table department rename to dept;

5. Add a Column to an Existing Table

The following examples adds deptid column to the existing employee table;

sqlite> alter table employee add column deptid integer;

Update the department id for the employees using update command as shown below.

update employee set deptid=3 where empid=101; 
update employee set deptid=2 where empid=102; 
update employee set deptid=2 where empid=103; 
update employee set deptid=1 where empid=104; 
update employee set deptid=2 where empid=105;

Verify that the deptid is updated properly in the employee table.

sqlite> select * from employee; 
101|John Smith|CEO|3 
102|Raj Reddy|Sysadmin|2 
103|Jason Bourne|Developer|2 
104|Jane Smith|Sale Manager|1 
105|Rita Patel|DBA|2

6. View all Tables in a Database

Execute the following command to view all the tables in the current database. The folowing example shows that there are two tables in the current database.

sqlite> .tables dept      employee

7. Create an Index

The following example creates an unique index called empidx on the empid field of employee table.

sqlite> create unique index empidx on employee(empid);

Once an unique index is created, if you try to add another record with an empid that already exists, you’ll get an error as shown below.

sqlite> insert into employee values (101,'James Bond','Secret Agent',1); 
Error: constraint failed

8. Create a Trigger

For this example, first add a date column called “updatedon” on employee table.

sqlite> alter table employee add column updatedon date;

Next, create a file that has the trigger definition. The following trigger will update the “updatedon” date column with the current timestamp whenever you perform an update on this table.

# vi employee_update_trg.sql
create trigger employee_update_trg after update on employee 
begin   
update employee set updatedon = datetime('NOW') where rowid = new.rowid; 
end;

Create the trigger on the company.db database as shown below.

# sqlite3 company.db < employee_update_trg.sql

Now anytime you update any record in the employee table, the “updatedon” date column will be updated with the current timestamp as shown below. The following example updates the “updatedon” timestamp for empid 104 through trigger.

# sqlite3 company.db 
sqlite> update employee set title='Sales Manager' where empid=104;  
sqlite> select * from employee; 
101|John Smith|CEO|3| 
102|Raj Reddy|Sysadmin|2| 
103|Jason Bourne|Developer|2| 
104|Jane Smith|Sales Manager|1|2012-09-15 18:29:28 105|Rita Patel|DBA|2|

9. Create a View

The following example creates a view called “empdept”, which combines fields from both employee and dept table.

sqlite> create view empdept as select empid, e.name, title, d.name, location from employee e, dept d where e.deptid = d.deptid;

Now you can execute select command on this view just like a regular table.

sqlite> select * from empdept; 
101|John Smith|CEO|Marketing|Los Angeles 
102|Raj Reddy|Sysadmin|Technology|San Jose 
103|Jason Bourne|Developer|Technology|San Jose 
104|Jane Smith|Sales Manager|Sales|Los Angeles 
105|Rita Patel|DBA|Technology|San Jose

After creating a view, if you execute .tables, you’ll also see the view name along with the tables.

sqlite> .tables 
deptempdept   employee

10. SQLite Savepoint, Rollback, Commit

Currently dept table has the following 3 records.

sqlite> select * from dept; 
1|Sales|Los Angeles 
2|Technology|San Jose 
3|Marketing|Los Angeles

Now, create a savepoint called “major”, and perform some transactions on the dept table. As you see below, we’ve added two records, deleted one record, after creating a savepoint called “major”.

sqlite> savepoint major;
sqlite> insert into dept values(4,'HR','Los Angeles'); 
sqlite> insert into dept values(5,'Finance','San Jose'); 
sqlite> delete from dept where deptid=1; 
sqlite> select * from dept; 
2|Technology|San Jose 
3|Marketing|Los Angeles 
4|HR|Los Angeles 
5|Finance|San Jose

Now for some reason, if we don’t want the above transactions, we can rollback the changes to a particular savepoint. In this example, we are rolling back all the changes we’ve made after the “major” savepoint.

sqlite> rollback to savepoint major; 
sqlite> select * from dept; 
1|Sales|Los Angeles 
2|Technology|San Jose 
3|Marketing|Los Angeles

If you don’t want your savepoints anymore, you can erase it using release command.

sqlite> release savepoint major;

11. Additional Date Functions

By default, the date columns values displayed in UTC time. To display in the local time, use the datetime command on the date column as shown below.

sqlite> select empid,datetime(updatedon,'localtime') from employee; 
104|2012-09-15 11:29:28

You can also use strftime to display the date column in various output.

sqlite> select empid,strftime('%d-%m-%Y %w %W',updatedon) from employee;
 104|19-09-2012 3 38

The following are the possible modifers you can use in the strftime function.

  • %d day of month: 00
  • %f fractional seconds: SS.SSS
  • %H hour: 00-24
  • %j day of year: 001-366
  • %J Julian day number
  • %m month: 01-12
  • %M minute: 00-59
  • %s seconds since 1970-01-01
  • %S seconds: 00-59
  • %w day of week 0-6 with Sunday==0
  • %W week of year: 00-53
  • %Y year: 0000-9999
  • %% %

12. Dropping Objects

You can drop all the above created objects using the appropriate drop command as shown below.

Since we are dropping objects for testing purpose, copy the company.db to a test.db and try these commands on the test.db

# cp company.db test.db  # 
sqlite3 test.db 
sqlite> .tables deptempdept   employee  
sqlite> drop index empidx; 
sqlite> drop trigger employee_update_trg; 
sqlite> drop view empdept; sqlite> 
drop table employee; 
sqlite> drop table dept;

All the tables and views from the test.db are now deleted.

sqlite> .tables 
sqlite>

Note: When you drop a table all the indexes and triggers for that table are also dropped.

13. Operators

The following are the possible operators you can use in SQL statements.

  • ||
  • * / %
  • + -
  • << >> & |
  • < >=
  • = == != <> IS IS NOT IN LIKE GLOB MATCH REGEXP
  • AND OR

For example:

sqlite> select * from employee where empid >= 102 and empid  select * from dept where location like 'Los%'; 
1|Sales|Los Angeles 
3|Marketing|Los Angeles

14. Explain Query Plan

Execute “explain query plan”, to get information about the table that is getting used in a query or view. This is very helpful when you are debugging a complex query with multiple joins on several tables.

sqlite> explain query plan select * from empdept; 0|0|TABLE employee AS e 1|1|TABLE dept AS d

For a detailed trace, just execute “explain” followed by the query to get more performance data on the query. This is helpful for debugging purpose when the query is slow.

sqlite> explain select empid,strftime('%d-%m-%Y %w %W',updatedon) from employee;
 0|Trace|0|0|0||00| 
1|Goto|0|12|0||00|
 2|OpenRead|0|2|0|4|00| 
3|Rewind|0|10|0||00| 
4|Column|0|0|1||00| 
5|String8|0|3|0|%d-%m-%Y %w %W|00| 
6|Column|0|3|4||00| 
7|Function|1|3|2|strftime(-1)|02| 
8|ResultRow|1|2|0||00| 
9|Next|0|4|0||01| 
10|Close|0|0|0||00| 
11|Halt|0|0|0||00| 
12|Transaction|0|0|0||00| 
13|VerifyCookie|0|19|0||00| 
14|TableLock|0|2|0|employee|00| 
15|Goto|0|2|0||00|

15. Attach and Detach Database

When you have multiple database, you can use attach command to execute queries across database.

For example, if you have two database that has the same table name with different data, you can create a union query across the database to view the combined records as explained below.

In this example, we have two company database (company1.db and company2.db). From the sqlite prompt, attach both these database by giving alias as c1 and c2 as shown below.

# sqlite3 sqlite> attach database 'company1.db' as c1; 
sqlite> attach database 'company2.db' as c2;

Execute “.database” command which will display all the attached databases.

sqlite> .database 
seq  name             file
 ---  ---------------  ------------------ 
0    main 
2    c1               /root/company1.db 
3    c2               /root/company2.db

Now, you can execute a union query across these databases to combine the results.

sqlite> select empid, name, title from c1.employee union select empid, name, title from c2.employee; 
101|John Smith|CEO 
102|Raj Reddy|Sysadmin 
103|Jason Bourne|Developer 
104|Jane Smith|Sales Manager 
105|Rita Patel|DBA 
201|James Bond|Secret Agent 
202|Spider Man|Action Hero

After attaching a database, from the current sqlite session, if you want to detach it, use detach command as shown below.

sqlite> detach c1;
 sqlite> .database
 seq name file
--- --------------- -----------------
0 main
2 c2 /root/company2.db
 

 

完! 

<think>首先,用户的问题是关于SQLite3中COMMIT SQL语句的使用方法及相关知识。用户提到了引用[1]、[2]、[3],这些引用提供了关于sqlite3_prepare、sqlite3_step、以及SQLite3的基本使用信息。用户之前的问题可能涉及SQLite3的操作,但当前问题聚焦在COMMIT语句上。 从系统级指令: - 所有行内数学表达式使用$...$格式。但这里涉及的是SQL语句,不是数学,所以可能不需要。 - 独立公式使用$$...$$单独成段。同样,可能不适用。 - LaTeX语法正确:确保任何公式正确。 - 使用中文回答。 - 生成相关问题:在回答后添加相关问题。 - 回答中引用的段落末尾自然地添加引用标识,例如[^1]。 - 回答结构清晰,帮助用户逐步解决问题,保证真实可靠。 用户提供的引用: - [^1]:讨论sqlite3_prepare和sqlite3_step,返回值如SQLITE_BUSY等。 - [^2]:显示Python代码使用SQLite3创建表、插入数据,最后有lists.commit()和lists.close()。 - [^3]:解释sqlite3.connect(),数据库打开和锁定机制。 用户当前问题:想了解SQLite3中COMMIT SQL语句的使用方法及相关知识。 关键点: - COMMIT语句在SQL中用于提交事务(transaction)。 - 在SQLite3中,事务管理是自动的(autocommit模式),但可以显式使用BEGIN、COMMIT、ROLLBACK来控制事务。 - 在用户提供的代码引用中,有lists.commit(),这是在Python sqlite3模块中的方法,对应于SQL的COMMIT语句。 所以,我应该解释: 1. 什么是COMMIT语句? 2. 在SQLite3中如何使用COMMIT? 3. 事务的概念:BEGIN、COMMIT、ROLLBACK。 4. 结合Python示例,因为引用中有Python代码。 结构化回答: - 逐步解释: a. 介绍事务的概念。 b. 解释COMMIT语句的作用。 c. 在SQLite3中的具体使用:SQL语法和Python API。 d. 示例代码。 e. 注意事项。 引用用户提供的引用: - 在[^2]中,有c.execute(...)后lists.commit(),这可以引用来说明在实际代码中如何使用。 - [^3]提到数据库连接和锁定,这与事务相关。 生成相关问题: - 基于COMMIT的主题,生成2-3个相关问题。 确保回答真实可靠: - 基于SQLite3官方文档知识:SQLite支持SQL标准的事务控制语句。 - COMMIT用于提交事务,使更改永久化。 - 在autocommit模式下,每个语句都是一个事务,但显式事务可以提高效率。 完整回答大纲: 1. **介绍事务和COMMIT**:解释为什么需要事务和COMMIT。 2. **SQL语法**:显示SQL语句如BEGIN TRANSACTION; ... COMMIT; 3. **Python中使用**:使用sqlite3模块的commit()方法。 4. **示例**:参考[^2]中的代码。 5. **注意事项**:如autocommit模式、锁定等。 6. **相关问题**。 最终输出格式: - 回答部分。 - §§相关问题§§部分。 </think> ### SQLite3中COMMIT SQL语句使用详解 在SQLite3中,`COMMIT`语句用于提交事务(transaction),将当前事务中的所有更改永久保存到数据库中。事务是一组作为原子操作执行的SQL语句序列:要么全部成功执行,要么全部回滚(撤销)。`COMMIT`确保数据的一致性和持久性,尤其在涉及多个修改操作时(如插入、更新或删除)。以下我将逐步解释其使用方法、相关概念及注意事项,并参考您提供的引用内容。 #### 1. **事务的基本概念** - **事务的作用**:事务通过`BEGIN TRANSACTION`(或简单`BEGIN`)启动,`COMMIT`结束。如果中途发生错误,可以使用`ROLLBACK`回滚所有更改。 - **原子性保证**:事务确保所有操作要么全部生效,要么全部无效。例如,在批量插入数据时,如果部分操作失败,`ROLLBACK`能恢复原始状态。 - **SQLite的自动提交模式**:默认情况下,SQLite3处于"自动提交"模式,即每个独立的SQL语句(如`INSERT`)被视为一个事务,执行后自动提交。但在复杂场景中,显式事务(使用`BEGIN`和`COMMIT`)能提升性能和可靠性。 #### 2. **COMMIT语句的SQL语法** `COMMIT`语句的SQL语法简单: ```sql BEGIN TRANSACTION; -- 执行多个SQL操作 (e.g., INSERT, UPDATE, DELETE) INSERT INTO table_name VALUES (...); UPDATE table_name SET column = value WHERE condition; COMMIT; -- 提交所有更改 ``` - **关键点**: - `BEGIN TRANSACTION`:标记事务开始。后续操作暂存于内存,不会立即写入磁盘。 - `COMMIT`:确认事务结束,将更改永久写入数据库文件。 - 如果省略`BEGIN`,SQLite会为每个语句自动开启和提交事务(效率较低)。 - **返回值**:在底层API中(如`sqlite3_step`),`COMMIT`执行可能返回状态码如`SQLITE_DONE`(成功)或`SQLITE_BUSY`(数据库忙)。例如,引用[^1]提到`sqlite3_step`返回`SQLITE_DONE`表示操作完成。 #### 3. **在Python中使用COMMIT(结合引用示例)** 在Python的`sqlite3`模块中,`COMMIT`通过连接对象的`commit()`方法实现,而非直接写SQL字符串。引用中的代码展示了典型用法: - **代码片段分析**: ```python import sqlite3 lists = sqlite3.connect(&#39;27.db&#39;) # 连接数据库 c = lists.cursor() # 执行多个操作 (e.g., 插入数据) for row in datainlist.iter_rows(...): cargo = [cell.value for cell in row] c.execute(data_truck, cargo) # 执行INSERT语句 lists.commit() # 提交事务,确保所有插入生效 lists.close() # 关闭连接 ``` - **解释**: - `lists.commit()`对应于SQL的`COMMIT`语句。它在所有`INSERT`操作后调用,将数据永久保存。 - 如果不调用`commit()`,更改仅在内存中,连接关闭后丢失(SQLite在连接关闭时自动回滚未提交事务)。 - 在事务中执行批量操作(如引用中的循环插入)能显著提升性能,减少磁盘I/O。 #### 4. **注意事项与最佳实践** - **错误处理**:在事务中,如果操作失败(如约束冲突),应捕获异常并调用`ROLLBACK`。例如: ```python try: lists.begin() # Python中显式开始事务 c.execute("INSERT ...") lists.commit() except sqlite3.Error: lists.rollback() # 回滚到BEGIN前的状态 ``` - **锁定机制**:引用提到,SQLite在事务提交时会对数据库加锁(如排他锁)。避免长时间事务以防`SQLITE_BUSY`错误。 - **性能优化**:对于批量操作,始终使用显式事务(`BEGIN`和`COMMIT`)。例如,引用中的代码通过事务一次性提交所有行,比自动提交模式快10-100倍。 - **autocommit控制**:在Python中,可通过`isolation_level=None`设置连接为自动提交模式(默认是延迟提交)。 #### 5. **总结** `COMMIT`是SQLite3事务管理的关键,确保数据修改的完整性和持久性。在SQL中直接使用`COMMIT`语句,或在Python中调用`commit()`方法。结合显式事务(`BEGIN`)能有效提升数据库操作效率和可靠性。参考您的代码示例,合理使用`COMMIT`可避免数据丢失并优化性能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值