以下程式碼為自己參考相關資料,並依個人常用的需求編寫出的常用函數,

包括新建資料庫、新建資料表、清除資料、新增資料到資料庫中、查詢資料 (讀取資料)、篩選查詢資料。

 

Step 1: 建立資料表並儲存為 DBHelper.java,Android 

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
 
public class DBHelper extends SQLiteOpenHelper {
    private static final String DB_NAME = "my.db";
    private static final int DB_VERSION = 1;
    private final static String _TableName = "Invoice_Item_Table"; //<-- table name
    public DBHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }
 
    @Override
    public void onCreate(SQLiteDatabase db) {
        final String SQL = "CREATE TABLE IF NOT EXISTS " + _TableName + "( " +
        "_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
        "_TITLE VARCHAR(50)" + ");";
        db.execSQL(SQL);
 
    }
 
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        final String SQL = "DROP TABLE " + _TableName;
        db.execSQL(SQL);
    }
}

Step 2: 初始化資料庫變數:

private DBHelper DH = null;
    private SQLiteDatabase db;
 
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        DH=new DBHelper(this);
        db = DH.getWritableDatabase();
    }

Step 3: 建立資料庫常用函數:

//Insert New record to Table
    private void add(String Title){
        ContentValues values = new ContentValues();
        values.put("_TITLE", Title.toString());
        db.insert("Invoice_Item_Table", null, values);
    }
 
    //read data from table
    public ArrayList<String> query_db_to_array()
    {
        list_Item.setAdapter(null);
        Cursor cursor = db.rawQuery("select * from Invoice_Item_Table", null);
 
        ArrayList<String> arrayStrings = new ArrayList<String>();
 
        while (cursor.moveToNext()) {
            String sItemName=cursor.getString(1);
            arrayStrings.add(sItemName);
        }
        cursor.close();
        return arrayStrings;
    }
 
    //clear table
    public void clear_db()
    {
        db.execSQL("delete from Invoice_Item_Table");
    }
 
    //close db
    private void closeDB()
    {
        DH.close();
    }
 
    @Override
    protected void onDestroy() {
        super.onDestroy();
        closeDB();
    }
arrow
arrow
    創作者介紹
    創作者 genlee 的頭像
    genlee

    不平凡,就不是生活

    genlee 發表在 痞客邦 留言(0) 人氣()