王立平--SQLite,SQLiteOpenHelper的簡單應用,sqliteopenhelper

來源:互聯網
上載者:User

王立平--SQLite,SQLiteOpenHelper的簡單應用,sqliteopenhelper

Android平台提供給我們一個資料庫輔助類來建立或開啟資料庫,這個輔助類繼承自SQLiteOpenHelper類,在該類的構造器中,調用Context中的方法建立並開啟一個指定名稱的資料庫物件。繼承和擴充SQLiteOpenHelper類主要做的工作就是重寫以下兩個 方法。

public class MySQLiteHelper extends SQLiteOpenHelper {
public MySQLiteHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
//資料庫首次建立時執行此方法,一般講建立表等初始化工作放在此處
//execSQL建立表
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
//建立表
String sql="create table if not exists hero_info("+ "id integer primary key,"+ "name varchar,"+ "level integer)";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub

}

MainActivity.java

package com.example.sqllite;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase; 
import android.graphics.Color;
import android.os.Bundle;
import android.widget.TextView; 
public class MainActivity extends Activity {
private TextView tv;
private MySQLiteHelper h;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }
    public void init(){
     tv=(TextView) findViewById(R.id.tv);
    h=new MySQLiteHelper(this, "my.db", null, 1);
    insertAndUpdateData(h);
    //查詢資料
    String result = queryData(h);
    tv.setTextColor(Color.RED);
    tv.setTextSize(20.0f);
    tv.setText("名字\t等級\n"+result);
   
   
    }
    
 
private void insertAndUpdateData(MySQLiteHelper helper) {
// TODO Auto-generated method stub

//調用getReadableDatabase 方法返回的並不總是唯讀資料庫物件,
//一般來說該方法和getWriteableDatabase 方法的返回情況相同,
//只有在資料庫僅開放唯讀許可權或磁碟已滿時才會返回一個唯讀資料庫物件。

    SQLiteDatabase db = helper.getWritableDatabase();
    //使用execSQL方法向表中插入資料
    db.execSQL("insert into hero_info(name,level) values('bb',0)");
    //使用insert方法向表中插入資料
    ContentValues values = new ContentValues();
    values.put("name", "xh");
    values.put("level", 5);
    //調用方法插入資料
    db.insert("hero_info", "id", values);
    //使用update方法更新表中的資料
    //清空ContentValues對象
    values.clear();
    values.put("name", "xh");
    values.put("level", 10);
    //更新xh的level 為10
    db.update("hero_info", values, "level = 5", null);
    //關閉SQLiteDatabase對象
    db.close();


//從資料庫中查詢資料
public String queryData(MySQLiteHelper myHelper){
String result = "";
//獲得資料庫物件
SQLiteDatabase db = myHelper.getReadableDatabase();
//查詢表中的資料
Cursor cursor = db.query("hero_info", null, null, null, null, null, "id asc");
//擷取name列的索引
int nameIndex = cursor.getColumnIndex("name");
//擷取level列的索引
int levelIndex = cursor.getColumnIndex("level");
for (cursor.moveToFirst();!(cursor.isAfterLast());cursor.moveToNext()) {
result = result + cursor.getString(nameIndex)+ "\t\t";
result = result + cursor.getInt(levelIndex)+"\n";
}
cursor.close();//關閉結果集
db.close();//關閉資料庫物件
return result;
}
@Override
protected void onDestroy() {
SQLiteDatabase db = h.getWritableDatabase();//擷取資料庫物件
//刪除hero_info表中所有的資料 傳入1 表示刪除所有行------>點擊back按鈕
db.delete("hero_info", "1", null);
super.onDestroy();
}



在Android開發中,為何要用SQLiteOpenHelper得到一個SQLiteDatabase資料庫,然後對資料庫進行操作

知道單例模式嗎?他的設計思想就是用了單例模式,當你有多個地方使用資料庫的時候只給你提供了一個串連,這樣既防止了起衝突又提高了效能
 
怎使用SQLite

以下是我看到的Kevin關於其使用的心得,原文的大體的意思是:Android例子涵蓋了一些Sqlite的基本用法,但它們並沒有深入地給出合理的使用方法,更重要的是,不合理的使用方法。大多數例子和文檔只是涉及最基本的資料庫查詢,或者教你如何建立一個ContentProvider。從來不提及的地方像: · 什麼地方建立和儲存SQLiteOpenHelper執行個體? · 可以有多少個執行個體? · 多線程同時訪問資料庫有沒有什麼要擔心的?基本的內容是,你可以任意次數地串連Sqlite資料庫,而且Android系統也支援你這樣做。Sqlite擁有檔案層級的鎖,用來同步訪問和防止錯誤。如果你只知道這些,那麼,將會給你帶來很大的痛苦。開源的一個好處是,你可以深入代碼一探究竟。從代碼和一些測試中,我瞭解到以下事實: · Sqlite擁有檔案層級的鎖。許多線程可以同時讀,但只有一個可以寫。鎖阻止多個同時寫入。 · Android在SQLiteDatabase中實現了一些java鎖來確保動作是同步進行。 · 如果你用多個線程瘋狂地訪問資料庫,你的資料庫不會(或不應該)崩潰。沒提到的是,如果你通過多個不同的真實串連同時寫資料庫,其中的某個會失敗,它不會等到前一個完成後繼續寫入。簡單地,不會寫入你的改變,更糟糕的是,你也得不到一個異常,只是在LogCat中輸出一些message,僅此而已。SQLiteOpenHelper類做了一些有趣的事。儘管它有方法可以獲得一個唯讀串連和可讀寫的串連,但實質上它們是同一個串連。假設沒有檔案寫錯誤的話,唯讀串連實質上就是一個可讀寫的串連。有趣吧。因此,如果你的app中使用一個helper的話,即便從多線程中使用,你也從未使用多個串連。同樣,一個helper中只有一個SQLiteDatabase的執行個體,這個執行個體中實現了一些java鎖。因此,當你正在執行資料庫的操作時,其它db的操作都將鎖定。即便是你使用多個線程來做這些事以便最佳化資料庫的效能,壞訊息,沒有什麼用。按照我的認識,SQLite工作的方式,基本上不可能會破壞你的資料庫,除非代碼裡有bug或者有硬體問題。因此,我推薦這樣使用:建立一個SQLiteOpenHelper靜態對象。什麼時候去close它呢?不需要。當app關閉,它會自動釋放檔案引用。但是,會不會有“close() was never explicitly called on database”異常呢?如果你注意的話,當串連掛在那裡的時候,你沒有得到那個異常。你只是在串連已經建立,而你又嘗試開啟另一個時才會有異常。因此,你只需要開啟一次串連。像這樣來使用:public class DatabaseHelper extends OrmLiteSqliteOpenHelper{ private static DatabaseHelper instance; public static synchronized DatabaseHelper getHelper(Context context) { if (instance == null) instance = new DatabaseHelper(context); return instance; }//Other stuff... } 就這些。。。
 

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.