android提供了一個名為sqlitedatabase的類,該類封裝了一些操作資料庫的api,使用該類可以完成對資料進行添加(create)、查詢(retrieve)、更新(update)和删除(delete)操作(這些操作簡稱為crud)
sqlite 目前支援 null,integer,real(浮點數字),text,blob(二進制文本)這5中資料類型。
sqlite 的資料庫檔案預設位于/data/data/package-name/databases 目錄下。
建立一個資料庫,首先要實作sqliteopenhelper的子類。建立mysqlhelper.java然後讓該類實作sqliteopenhelper這個抽象類。
package com.alpha.sqlite;
import android.content.context;
import android.database.sqlite.sqlitedatabase;
import android.database.sqlite.sqlitedatabase.cursorfactory;
import android.database.sqlite.sqliteopenhelper;
public class mysqlhelper extends sqliteopenhelper {
public mysqlhelper(context context, string name, cursorfactory factory,
int version) {
super(context, name, factory, version);
// todo auto-generated constructor stub
}
@override
public void oncreate(sqlitedatabase db) {
// todo auto-generated method stub
//建立一個資料庫及表格 3個字段如下
//primary key 字段為主鍵 主鍵:表中經常有一個列或列的組合,其值能唯一地辨別表中的每一行。這樣的一列或多列稱為表的主鍵
db.execsql("create table mytable(id integer primary key autoincrement,name text,age text)");
public void onupgrade(sqlitedatabase arg0, int arg1, int arg2) {
上述代碼成功的建立了 sqliteopenhelper 的子類 mysqlhelper 然後分别實作了其成員方法 在oncreate方法中 初始化資料庫及字段。
private mysqlhelper mysql;
private sqlitedatabase db;
mysql=new mysqlhelper(mainactivity.this,"mydb",null,1);
db=mysql.getreadabledatabase(); //推薦使用此種方法打開
getreadabledatabase()方法建立的資料庫首先以讀寫方式打開資料庫,如果使用者來存儲資料庫的磁盤空間已經滿了,則會打開失敗,然後重新以隻讀方式打開。
getwritabledatabase()方法建立的資料庫首先以讀寫方式打開資料庫,如果使用者來存儲資料庫的磁盤空間已經滿了,則會報錯。
是以,建議用getreadabledatabase()來建立資料庫的執行個體
向資料庫中增加資料:兩種方法
第一種用系統提供的api函數添加
contentvalues cv=new contentvalues();
//cv.put("id",1); //id是主鍵 自增長的 可以不指派
cv.put("name","上帝");
cv.put("age","27");
db.insert("mytable",null,cv);
db.close();
第二種方法用資料庫語句
db.execsql("insert into mytable(name,age) values(?,?)",new object[]{"上帝","27"});
db.close();
兩種方法都可以
删除資料兩種方法
第一種方法
db.execsql("delete from mytable where id=2"); //删除id=2的那一行
db.execsql("delete from mytable where name=?", new object[]{"上帝"}); //删除符合字段name=上帝的所有行
第二種方法
db.delete("mytable",null,null); //删除資料表裡所有的資料
db.delete("mytable","id=?",new string[]{"2"}); //删除資料表mytable中字段 id=2的一整行
修改資料兩種方法
db.execsql("update mytable set name='神',age='23' where id=2"); //注意此處id位 主鍵 不可修改
//db.execsql("update mytable set name='艾尼路',age='25' where name=?",new object[]{"上帝"});
cv.put("name","艾斯");
cv.put("age","21");
db.update("mytable",cv,"id=?",new string[]{"5"});
查詢資料庫
cursor cursor=db.query("mytable",new string[]{"id","name","age"},null,null,null,null,null);
while(cursor.movetonext()) //指向下一行
{
int idindex=cursor.getcolumnindex("id");
int id=cursor.getint(idindex);
int nameindex=cursor.getcolumnindex("name");
string name=cursor.getstring(nameindex);
int ageindex=cursor.getcolumnindex("age");
string age=cursor.getstring(ageindex);
string result=id+" "+name+" "+age;
log.i("result",result); //列印日志
列印的日志如下
所有對資料庫的操作最後都要