转自: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 alsoinstall SQLite database from sourceto get the latest version.
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,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.db2. 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.
# 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.sql3. 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 Angeles4. 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|26. 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 employee7. 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 Failed8. 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.sqlcreate 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 employee10. 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.
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 ObjectsYou 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. OperatorsThe following are the possible operators you can use in sql statements.
|| * / % + - << >> & | < >= = == != <> IS IS NOT IN liKE GLOB MATCH REGEXP AND ORFor example:
sqlite> select * from employee where empID >= 102 and empID select * from dept where location like 'Los%'; 1|Sales|Los Angeles 3|Marketing|Los Angeles14. Explain query PlanExecute “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 dFor 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,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 DatabaseWhen 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
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完!
总结以上是内存溢出为你收集整理的15条SQLite3语句全部内容,希望文章能够帮你解决15条SQLite3语句所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)