04 September 2010
android insert value to DB、select value from DB

這篇文章會介紹

如何新增資料到sqllite database,並在database作查詢等動作

上一篇已經介紹如何在sd card新增資料庫

這裡就只略過如何新增資料庫,直接說明新增and查詢的動作

public class db_sample {
public static final String STR_TABLE_NAME = "table_name"; //table名稱
public static final String STR_FIELD_ID = "field_id"; //欄位名稱
public static final String STR_FIELD_NAME = "field_name"; //欄位名稱
private static Context context;

public db_sample(Context context) {
this.context = context; //new這個class時,一定要傳入context,因為openOrCreateDatabase是由context底下的method
}

//建立table的method
public static final void fnCreateDB(){
//MODE_WORLD_WRITEABLE,只能有寫的權限
SQLiteDatabase dbwrite
= context.openOrCreateDatabase("/sdcard/hi_test.db", context.MODE_WORLD_WRITEABLE, null);

//建立table
String sql =
String.format("CREATE TABLE %s (%s INTEGER primary key autoincrement, %s text )"
, STR_TABLE_NAME
, STR_FIELD_ID
, STR_FIELD_NAME
);
dbwrite.execSQL(sql);
}

//新增資料的method
public static final long fnInsert(String strText){
SQLiteDatabase dbwrite
= context.openOrCreateDatabase("/sdcard/hi_test.db", context.MODE_WORLD_WRITEABLE, null);
ContentValues cv = new ContentValues();
cv.put(STR_FIELD_NAME, strText);
return dbwrite.insert(STR_TABLE_NAME, null, cv);//如果return -1代表有錯誤,否則會return該筆資料在第幾列
}

//撈資料的method
public static final int fnRead(String strText){
//MODE_WORLD_WRITEABLE,只能有讀取的權限
SQLiteDatabase dbread
= context.openOrCreateDatabase("/sdcard/hi_test.db",context. MODE_WORLD_READABLE, null);


Cursor cursor
= dbread.rawQuery(
"select "+STR_FIELD_ID+" from "+STR_TABLE_NAME+" where "+STR_FIELD_NAME+"=?",
new String[] {strText}
);

if (cursor.moveToFirst()) {
return cursor.getInt(0);
}
return -1;
}

}




呼叫方法就如下:

public class test extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db_sample db = new db_sample(this);
db.fnCreateDB();
db.fnInsert("HI");
int iID = db.fnRead("HI");
}

}


blog comments powered by Disqus