SQLite 是一個開源的嵌入式關聯式資料庫,實現自包容、零配置、支援事務的SQL資料庫引擎。 其特點是高度便攜、使用方便、結構緊湊、高效、可靠。 與其他資料庫管理系統不同,SQLite 的安裝和運行非常簡單,在大多數情況下 - 只要確保SQLite的二進位檔案存在即可開始建立、串連和使用資料庫。如果您正在尋找一個嵌入式資料庫專案或解決方案,SQLite是絕對值得考慮。轉載http://www.lupaworld.com/article-217676-1.html,原文有些錯誤,本文已經改正,以後還會持續更新。 2. 安裝 SQLite on Windows
- 進入 SQL 下載頁面:http://www.sqlite.org/download.html
- 下載 Windows 下的先行編譯二進位檔案包:
- sqlite-shell-win32-x86-<build#>.zip
- sqlite-dll-win32-x86-<build#>.zip
注意: <build#> 是 sqlite 的編譯版本號碼
- 將 zip 檔案解壓到你的磁碟,並將解壓後的目錄添加到系統的 PATH 變數中,以方便在命令列中執行 sqlite 命令。
- 可選: 如果你計劃發布基於 sqlite 資料庫的應用程式,你還需要下載源碼以便編譯和利用其 API
- sqlite-amalgamation-<build#>.zip
SQLite on Linux 在 多個 Linux 發行版提供了方便的命令來擷取 SQLite: /* For Debian or Ubuntu /*$ sudo apt-get install sqlite3 sqlite3-dev/* For RedHat, CentOS, or Fedora/*$ yum install SQLite3 sqlite3-dev SQLite on Mac OS X 如果你正在使用 Mac OS 雪豹或者更新版本的系統,那麼系統上已經裝有 SQLite 了。 3. 建立首個 SQLite 資料庫
現在你已經安裝了 SQLite 資料庫,接下來我們建立首個資料庫。在命令列視窗中輸入如下命令來建立一個名為 test.db 的資料庫。 sqlite3 test.db 建立表: sqlite> create table mytable(id integer primary key, value text); 該表包含一個名為 id 的主鍵欄位和一個名為 value 的文字欄位。 注意: 最少必須為建立的資料庫建立一個表或者視圖,這麼才能將資料庫儲存到磁碟中,否則資料庫不會被建立。 接下來往表裡中寫入一些資料: sqlite> insert into mytable(id, value) values(1, ‘Micheal‘);sqlite> insert into mytable(id, value) values(2, ‘Jenny‘);sqlite> insert into mytable(value) values(‘Francis‘);sqlite> insert into mytable(value) values(‘Kerk‘); 查詢資料:sqlite> select * from mytable;1|Micheal2|Jenny3|Francis4|Kerk 設定格式化查詢結果:sqlite> .mode columnsqlite> .header onsqlite> select * from test;id value----------- -------------1 Micheal2 Jenny3 Francis4 Kerk .mode column 將設定為列顯示模式,.header 將顯示列名。 修改表結構,增加列: sqlite> alter table mytable add column email text not null ‘‘ collate nocase;; 建立視圖:sqlite> create view nameview as select * from mytable; 建立索引:sqlite> create index test_idx on mytable(value); 4. 一些有用的 SQLite 命令
顯示表結構: sqlite> .schema [table] 擷取所有表和視圖:sqlite > .tables
擷取指定表的索引列表:sqlite > .indices [table ] 匯出資料庫到 SQL 檔案:sqlite > .output [filename ] sqlite > .dump sqlite > .output stdout 從 SQL 檔案匯入資料庫:sqlite > .read [filename ] 格式化輸出資料到 CSV 格式:sqlite >.output [filename.csv ] sqlite >.separator , sqlite > select * from test; sqlite >.output stdout 從 CSV 檔案匯入資料到表中:sqlite >create table newtable ( id integer primary key, value text ); sqlite >.import [filename.csv ] newtable
備份資料庫: /* usage: sqlite3 [database] .dump > [filename] */ sqlite3 mytable.db .dump > backup.sql 恢複資料庫:/* usage: sqlite3 [database ] < [filename ] */ sqlite3 mytable.db < backup.sql |