sqlite3命令详解

http://www.2cto.com/database/201112/113683.html


sqlite3可以让我们手动的对SQLite数据库进行管理。一共有2个sqlite3,一个在电脑上,它位于android-sdk-windows\tools\sqlite3.exe,用于电脑上SQLite数据库进行管理;还有一个位于android系统上(手机上),它用于位于Android系统上的SQLite数据库进行管理,对于后者你需要通过adb shell进入shell。有时我们不想直接在android系统上对SQLite数据库进行操作,这时可以把它拷贝到电脑上进行操作。

但是需要注意前者是window系统,后者是Linux系统,他们表示路径的方式不一样。

  在sqlite3命令后可跟一个参数指定要打开或创建的数据库文件。如果指定的数据库文件还不存在,就会新建一个数据库,且以该参数作为文件名。对于android系统上的sqlite3,必须通过其shell来运行,如果新建数据库的话,需要root权限,可以在shell中键入"su"来获得root权限。

如果是android系统的sqlite3程序(通过shell运行),你可以Ctrl键+D ,然后回车退出该程序回到shell,也可以Ctrl键+C直接退出Shell,如果是电脑上的sqlite3,可以Ctrl键+C直接退出sqlite3程序。

下面就是一个创建包含一个名叫"tbl1"的表的名叫"ex1"的SQLite数据库的示例。

示例1:

$ sqlite3 ex1

SQLite version 3.3.10

Enter ".help" for instructions

sqlite> create table tbl1(one varchar(10), two smallint);

sqlite> insert into tbl1 values('hello!',10);

sqlite> insert into tbl1 values('goodbye', 20);

sqlite> select * from tbl1;

hello!|10

goodbye|20

sqlite>

sqlite3支持两种命令,一种是SQL命令,一种是非SQL命令,非SQL命令以"."作为前缀,比如".tables"命令。

可以通过".help"命令来查看它所有的非SQL命令.所有不以"."为前缀的语句,都将做SQL进行解释,当时对于SQL语句你需要在末尾加上分号";"以表示SQL语句输入完成,这时你输入的命令才开始按照SQL语言进行执行。

比如,示例2:

sqlite> CREATE TABLE tbl2 (

   ...>   f1 varchar(30) primary key,

   ...>   f2 text,

   ...>   f3 real

   ...> );

sqlite>

关于数据库的schema是存放在一个叫sqlite_master的表中,你虽然不能对它进行DROP TABLE, UPDATE, INSERT or DELETE操作,但是可以像普通的表一样对它进行查询。

比如,示例3:

sqlite3 /data/data/com.android.providers.settings/databases/settings.db

SQLite version 3.6.22

Enter ".help" for instructions

Enter SQL statements terminated with a ";"

sqlite> .tables

.tables

android_metadata   bookmarks          system

bluetooth_devices  secure

sqlite> select * from sqlite_master;

select * from sqlite_master;

table|android_metadata|android_metadata|3|CREATE TABLE android_metadata (locale

TEXT)

table|system|system|4|CREATE TABLE system (_id INTEGER PRIMARY KEY AUTOINCREMENT

,name TEXT UNIQUE ON CONFLICT REPLACE,value TEXT)

index|sqlite_autoindex_system_1|system|5|

table|sqlite_sequence|sqlite_sequence|6|CREATE TABLE sqlite_sequence(name,seq)

index|systemIndex1|system|7|CREATE INDEX systemIndex1 ON system (name)

table|secure|secure|8|CREATE TABLE secure (_id INTEGER PRIMARY KEY AUTOINCREMENT

,name TEXT UNIQUE ON CONFLICT REPLACE,value TEXT)

index|sqlite_autoindex_secure_1|secure|9|

index|secureIndex1|secure|10|CREATE INDEX secureIndex1 ON secure (name)

table|bluetooth_devices|bluetooth_devices|11|CREATE TABLE bluetooth_devices (_id

 INTEGER PRIMARY KEY,name TEXT,addr TEXT,channel INTEGER,type INTEGER)

table|bookmarks|bookmarks|12|CREATE TABLE bookmarks (_id INTEGER PRIMARY KEY,tit

le TEXT,folder TEXT,intent TEXT,shortcut INTEGER,ordering INTEGER)

index|bookmarksIndex1|bookmarks|13|CREATE INDEX bookmarksIndex1 ON bookmarks (fo

lder)

index|bookmarksIndex2|bookmarks|14|CREATE INDEX bookmarksIndex2 ON bookmarks (sh

ortcut)

sqlite>

关于TEMPORARY tables的schema并没有保存在"sqlite_master" 表中,因为TEMPORARY表只对创建它的applications可见.

关于TEMPORARY tables的schema保存在另外一个名叫"sqlite_temp_master"的表中. The "sqlite_temp_master" table is temporary itself.

 


在sqlite3中我们可以通过".help"命令来查所有的非SQL命令。

比如,示例4:

sqlite> .help

.help

.backup ?DB? FILE      Backup DB (default "main") to FILE

.bail ON|OFF               Stop after hitting an error.  Default OFF

.databases                  List names and files of attached databases

.dump ?TABLE? ...      Dump the database in an SQL text format

                                   If TABLE specified, only dump tables matching

                                   LIKE pattern TABLE.

.echo ON|OFF            Turn command echo on or off

.exit                             Exit this program

.explain ?ON|OFF?      Turn output mode suitable for EXPLAIN on or off.

                                    With no args, it turns EXPLAIN on.

.genfkey ?OPTIONS?     Options are:

                                      --no-drop: Do not drop old fkey triggers.

                                      --ignore-errors: Ignore tables with fkey errors

                                     --exec: Execute generated SQL immediately

                                         See file tool/genfkey.README in the source

                                          distribution for further information.

.header(s) ON|OFF      Turn display of headers on or off

.help                               Show this message

.import FILE TABLE     Import data from FILE into TABLE

.indices ?TABLE?        Show names of all indices

                                     If TABLE specified, only show indices for tables

                                       matching LIKE pattern TABLE.

.load FILE ?ENTRY?     Load an extension library

.log FILE|off                  Turn logging on or off.  FILE can be stderr/stdout

.mode MODE ?TABLE?     Set output mode where MODE is one of:

                                          csv      Comma-separated values

                                          column   Left-aligned columns.  (See .width)

                                          html     HTML <table> code

                                          insert   SQL insert statements for TABLE

                                          line     One value per line

                                         list     Values delimited by .separator string

                                         tabs     Tab-separated values

                                         tcl      TCL list elements

.nullvalue STRING      Print STRING in place of NULL values

.output FILENAME       Send output to FILENAME

.output stdout                Send output to the screen

.prompt MAIN CONTINUE  Replace the standard prompts

.quit                                  Exit this program

.read FILENAME              Execute SQL in FILENAME

.restore ?DB? FILE          Restore content of DB (default "main") from FILE

.schema ?TABLE?        Show the CREATE statements

                                        If TABLE specified, only show tables matching

                                          LIKE pattern TABLE.

.separator STRING      Change separator used by output mode and .import

.show                           Show the current values for various settings

.tables ?TABLE?         List names of tables

                                  If TABLE specified, only list tables matching

                                   LIKE pattern TABLE.

.timeout MS                Try opening locked tables for MS milliseconds

.width NUM1 NUM2 ...   Set column widths for "column" mode

.timer ON|OFF              Turn the CPU timer measurement on or off

sqlite>

sqlite3能以8种不同的方式显示查询返回的结果:"csv", "column", "html", "insert", "line", "list","tabs",  "tcl".

你可以通过.mode来设置显示的方式。默认的是"list"方式,这时返回结果的一条记录显示一行,每列的内容之间用设定的分隔符隔开,

默认的分隔符是"|".

示例5:

sqlite> .mode list

sqlite> select * from tbl1;

hello|10

goodbye|20

sqlite>

你可以通过".separator"来设置"list"模式下的分隔符。比如我们想把", "作为分隔符,可以这样:

示例6:

sqlite> .separator ", "

sqlite> select * from tbl1;

hello, 10

goodbye, 20

sqlite>

"line"模式下, 每行只显示数据库的一行的一列。每行由列名,等号和列的值组成。每条记录之间由一个空行隔开。

比如,示例7

sqlite> .mode line

sqlite> select * from tbl1;

one = hello

two = 10

 

one = goodbye

two = 20

sqlite>

"column"模式下,每条记录都在单独一行显示。第一行显示的是列名,第二行只是用于分割列名和记录的数据,第三行开始才是记录的内容。

比如,示例8:

sqlite> .mode column

sqlite> select * from tbl1;

one         two      

----------  ----------

hello       10       

goodbye     20       

sqlite>

默认情况下,每列的宽度最多只能显示10个字符。所以如果数据包含的字符如果他太多,可能就显示不完。

但是我们可以通过".width"设置每列的宽度。

比如,示例9:

sqlite> .width 12 6

sqlite> select * from tbl1;

one           two  

------------  ------

hello         10   

goodbye       20   

sqlite>

示例9就把第1列和第二列的宽度分别设置为了12和6个字符,其他列的宽度并没改变。

如果你把列宽设置为0,那么调整为以下三个的最大值:10,该列的列名字符数,第一行记录该列的字符数。这样列的宽度就可以自动调整。

默认的列宽就是0,以便它可以自动调整。

可以通过".header"命令可以设置是否显示头(头包括第一行,列名,第二行,分隔行)。

比如,示例10:

sqlite> .header off

sqlite> select * from tbl1;

hello         10   

goodbye       20   

sqlite>

"insert"模式下,返回的查询结果将以SQL的INSERT语句形式进行显示。

比如,示例11:

sqlite> .mode insert new_table

sqlite> select * from tbl1;

INSERT INTO 'new_table' VALUES('hello',10);

INSERT INTO 'new_table' VALUES('goodbye',20);

sqlite>

"html"模式下,查询返回结果将以XHTML table的形式进行显示,

它并不以<TABLE>作为开头和</TABLE>作为结尾。 但是每条记录以<TR>作为开始,</TR>作为结束,记录的数据以<TD>作为开始,以</TD>作为结束

比如,示例12:

sqlite> select * from system;

select * from system;

<TR><TD>1</TD>

<TD>volume_music</TD>

<TD>7</TD>

</TR>

<TR><TD>4</TD>

<TD>volume_voice</TD>

<TD>4</TD>

</TR>

........省略.........

sqlite>

".output"命令可以把查询返回结果的输出定向到文件上。该命令的第一个参数即是要定向的位置。在把输出定向了文件后,可以通过".output stdout"把输出重新定向到标准输出上。

示例13:

sqlite> .mode list

sqlite> .separator |

sqlite> .output test_file_1.txt

sqlite> select * from tbl1;

sqlite> .exit

$ cat test_file_1.txt

hello|10

goodbye|20

$



 

sqlite3提供了多个命令来查看数据库的schema

".tables"命令可以查看当前数据库所有的表

比如,示例14:

sqlite> .tables

tbl1

tbl2

sqlite>

".tables"和在list模式下执行下面的语句相似:

SELECT name FROM sqlite_master  WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%' UNION ALL  SELECT name FROM sqlite_temp_master  WHERE type IN ('table','view')  ORDER BY 1

实际上, 如果你查看sqlite3程序的源码(found in the source tree in the file src/shell.c),you'll find exactly the above query.

另外,".tables"命令后也可以跟一参数,它是一个pattern,这样命令就只列出表名和该参数匹配的表。

比如,示例14-1:

sqlite> .tables

.tables

android_metadata   bookmarks          system

bluetooth_devices  secure

sqlite> .tables s%

.tables s%

secure           sqlite_sequence  system

sqlite>

".indices"命令列出指定表的所有indices(索引)。第一个参数为表的名字。

比如,示例15:

sqlite> .schema system

.schema system

CREATE TABLE system (_id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT UNIQUE ON C

ONFLICT REPLACE,value TEXT);

CREATE INDEX systemIndex1 ON system (name);

sqlite> .tables

.tables

android_metadata   bookmarks          system

bluetooth_devices  secure

sqlite> .indices system

.indices system

sqlite_autoindex_system_1

systemIndex1

sqlite>

".schema"命令,在没有参数的情况,它会显示最初用于创建数据库的CREATE TABLE和CREATE INDEX的SQL语句。比如,示例16

".schema"命令可以包含一个参数,它是一个pattern,用于对表进行过滤,这时只会显示满足条件的表和所有索引的SQL语句。

比如,示例15和示例17.

示例16:

sqlite> .schema

.schema

CREATE TABLE android_metadata (locale TEXT);

CREATE TABLE bluetooth_devices (_id INTEGER PRIMARY KEY,name TEXT,addr TEXT,chan

nel INTEGER,type INTEGER);

CREATE TABLE bookmarks (_id INTEGER PRIMARY KEY,title TEXT,folder TEXT,intent TE

XT,shortcut INTEGER,ordering INTEGER);

CREATE TABLE secure (_id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT UNIQUE ON C

ONFLICT REPLACE,value TEXT);

CREATE TABLE system (_id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT UNIQUE ON C

ONFLICT REPLACE,value TEXT);

CREATE INDEX bookmarksIndex1 ON bookmarks (folder);

CREATE INDEX bookmarksIndex2 ON bookmarks (shortcut);

CREATE INDEX secureIndex1 ON secure (name);

CREATE INDEX systemIndex1 ON system (name);

sqlite>

示例17:

sqlite> .schema s%

.schema s%

CREATE TABLE secure (_id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT UNIQUE ON C

ONFLICT REPLACE,value TEXT);

CREATE TABLE sqlite_sequence(name,seq);

CREATE TABLE system (_id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT UNIQUE ON C

ONFLICT REPLACE,value TEXT);

CREATE INDEX secureIndex1 ON secure (name);

CREATE INDEX systemIndex1 ON system (name);

sqlite>

".schema"命令功能和下面的语句相似:

SELECT sql FROM     (SELECT * FROM sqlite_master UNION ALL     SELECT * FROM sqlite_temp_master) WHERE type!='meta' ORDER BY tbl_name, type DESC, name

如果你传了一个参数给".schema",以表明只想得到表的schema而包括索引的schema,那么SQL语句应该如下:

SELECT sql FROM    (SELECT * FROM sqlite_master UNION ALL     SELECT * FROM sqlite_temp_master) WHERE type!='meta' AND sql NOT NULL AND name NOT LIKE 'sqlite_%' ORDER BY substr(type,2,1), name

如果你想 “.schema”支持参数. 那么SQL语句应该如下:

SELECT sql FROM    (SELECT * FROM sqlite_master UNION ALL     SELECT * FROM sqlite_temp_master) WHERE tbl_name LIKE '%s'   AND type!='meta' AND sql NOT NULL AND name NOT LIKE 'sqlite_%' ORDER BY substr(type,2,1), name

这里SQL语句中的"%s"将被你传入的参数代替. 你就可以只显示一部分的schema.

事实上".tables"的也是采用这种"LIKE"的方式,进行pattern查询的。

".databases"命令将列出当前connection中所有的数据库。

一般至少包含2个,一个是"main", the original database opened.另一个是"temp", the database used for temporary tables.

 There may be additional databases listed for databases attached using the ATTACH statement.

 The first output column is the name the database is attached with, and the second column is the filename of the external file.

".dump"命令将把database的内容转化为一个ASCII编码的文本文件。

This file can be converted back into a database by piping it back into sqlite3.

把一个数据库进行archival备份可以用如下的命令:

$ echo '.dump' | sqlite3 ex1 | gzip -c >ex1.dump.gz

这样将生产一个名叫ex1.dump.gz的文件,它包含了重新构建数据库的所有信息

重新构建数据库。只需要如下的语句: www.2cto.com

$ zcat ex1.dump.gz | sqlite3 ex2

因为文本格式是纯SQL的 ,所以你可以通过.dump命令把你的数据库导入到另外的更常用的数据库引擎.

比如:

$ createdb ex2

$ sqlite3 ex1 .dump | psql ex2

The ".explain" dot command can be used to set the output mode to "column" and

to set the column widths to values that are reasonable for looking at the output of an EXPLAIN command.

The EXPLAIN command is an SQLite-specific SQL extension that is useful for debugging.

If any regular SQL is prefaced by EXPLAIN, then the SQL command is parsed and analyzed but is not executed.

Instead, the sequence of virtual machine instructions that would have been used to execute the SQL command are returned like a query result.

For example:

 

sqlite> .explain

sqlite> explain delete from tbl1 where two<20;

addr  opcode        p1     p2     p3         

----  ------------  -----  -----  -------------------------------------  

0     ListOpen      0      0                 

1     Open          0      1      tbl1       

2     Next          0      9                 

3     Field         0      1                 

4     Integer       20     0                 

5     Ge            0      2                 

6     Key           0      0                 

7     ListWrite     0      0                 

8     Goto          0      2                 

9     Noop          0      0                  

10    ListRewind    0      0                 

11    ListRead      0      14                

12    Delete        0      0                 

13    Goto          0      11                

14    ListClose     0      0

The ".timeout" command sets the amount of time that the sqlite3 program will wait for locks to clear on files it is trying to access before returning an error. The default value of the timeout is zero so that an error is returned immediately if any needed database table or index is locked.

 ".exit和“.quite"命令用于退出sqlite3程序.他们好像没有什么区别

如何以Shell脚本的方式使用sqlite3命令

一种方式是:用"echo"或"cat"命令输出一些sqlite3命令到一个文件,然后执行程序sqlite3,并把该文件作为sqlite3的输入流。这种方式不错,很多程序都可以这样。

另一种方式是:以SQL语句作为sqlite3的第二个参数,在执行SQL操作。为了方便,sqlite3允许在第一个参数数据库名后,再跟一个参数,来指定要执行的SQL语句。如果sqlite3带2个参数进行启动的话,第二个参数将做为SQL传递给SQLite library来处理, 返回结果将以list模式在标准输出中进行显示,然后sqlite3程序也退出了。

比如,示例17:

# sqlite3 /data/data/com.android.providers.settings/databases/settings.db "select * from system;select * from system"

以SQL语句作为sqlite3的第二个参数,这种方式主要是为了sqlite3和其他程序(比如"awk")联合使用.

比如,示例18:

$ sqlite3 ex1 'select * from tbl1' |

> awk '{printf "<tr><td>%s<td>%s\n",$1,$2 }'

<tr><td>hello<td>10

<tr><td>goodbye<td>20

$

SQL语句的结束符

一般sqlite3的SQL语句的结束符是分号";". 然而你在shell中运行sqlite3时你还可以使用"GO" (大写) 或"/"来作为一条SQL语句结束的标志. 他们分别在SQL Server和Oracle中被使用. 但是他在sqlite3_exec()不能使用shell会先把他们转化为分号";",然后再传递到该函数.

在源码中编译sqlite3

The sqlite3 program is built automatically when you compile the 当你编译SQLite library的时候,sqlite程序就自动被编译了. Just get a copy of the source tree, run "configure" and then "make".



你可能感兴趣的:(sql,sqlite,table,Integer,conflict,bookmarks)