2010年10月5日 星期二

Android程式設計 (十六) 使用SQLite (1)

SQLite是一種專為嵌入式系統設計的關聯式資料庫,支援標準的SQL-92作業,具備簡潔、佔用系統資源小等優點。此外SQLite的資料庫是以單一檔案的形式儲存;使用時,只要在編譯程式的時候將程式庫一起編譯就可以了,不需要另外安裝資料庫伺服器軟體,所以要複製資料庫或移植到其它電腦都相當容易。
SQLite官網可下載SQLite程式,包括Mac、Linux及Windows版本,網址:http://www.sqlite.org/download.html
SQLite基本操作
所有的SQL指令都是以分號(;)結尾的。如果遇到兩個減號(--)則代表註解,SQLite會略過去。
建立資料庫檔案
假設我們要建立一個名為demo.db的資料庫,只要在命令列鍵入sqlite3 demo.db。如果目錄下沒有db_name這個資料庫,即會建立db_name資料庫,並進入SQLite作業模式;此時,命令列提示會變成sqlite>
D:\SQLite> sqlite3 demo.db
建立資料表
sqlite> create table address(name, email, tel);
上述指令建立了一個名叫address的資料表,裡面有name、email及tel三個資料欄。
加入一筆資料
sqlite> insert into address values ('tina', 'tina@email.net', '1111');
sqlite> insert into address values ('tony', 'tony@email.net', '2222');
sqlite> insert into address values ('mike', 'mike@email.net', '4444');
如果該欄位沒有資料,我們可以填NULL。
查詢資料
sqlite> select * from address where name = 'tina';
sqlite> select * from address limit 2;
sqlite> select count(*) from address;
更改資料
sqlite> update address set tel = '3333' where name = 'mike';