大體步驟:
創建SQLiteDatabase對象
通過重寫SQLiteHelper類,執行增刪減操作
- 寫構造方法
- onCreate()方法,即第一次使用這個表時,調用的方法(一般建表的語句)
- onUpgrade()方法,版本更新時調用
直接執行查詢操作(返回值爲遊標)
調用moveToXX()方法對遊標直接找到相關數據,返回布爾值(遊標可滾動,不需要While())
實例代碼:
重寫SQLiteHelper類
<span style="font-size:14px;">package com.study.entity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class Dao extends SQLiteOpenHelper {
public Dao(Context context) {
super(context, "db_con", null, 1);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase sdb) {
// TODO Auto-generated method stub
sdb.execSQL("CREATE TABLE t_contact(_id intger primary key autoincrement,name varchar(50),phone varchar(50) ");
sdb.execSQL("insert into t_contact(name,phone)values('williammu','18297927880')");
}
@Override
public void onUpgrade(SQLiteDatabase sdb, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
// if (oldVersion == 1 && newVersion == 2) {
//
// }
}
/**
* 得到所有聯繫人
*
* @return Cursor
*/
public Cursor getAll() {
SQLiteDatabase sdb = getReadableDatabase();
Cursor cur = sdb.rawQuery("SELECT * FROM t_contact", null);
return cur;
}
/**
* 增加聯繫人
*/
public void insertContacts() {
Contact contact=new Contact();
SQLiteDatabase sdb = getWritableDatabase();
sdb.execSQL("INSERT INTO t_contact (name,phone) VALUES ('"+contact.getName()+"','"+contact.getPhone()+"')");
}
}
</span>
謝謝。