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".
與50位技術專家面對面20年技術見證,附贈技術全景圖
總結
以上是生活随笔為你收集整理的sqlite3命令详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: cgic: 为C语言编写CGI的C函数库
- 下一篇: qq2440 cs8900移植