Android爲了讓咱們可以更加方便地管理數據庫,專門提供了一個SQLiteOpenHelper幫助
類,藉助這個類就能夠常常簡單地對數據庫進⾏建立和升級。既然有好東西能夠直接使用,那
咱們固然要嘗試一下了,下面我就將對SQLiteOpenHelper的基本用法進行介紹。
瘦先你要知道SQLiteOpenHelper是一個抽象類,這意味着若是咱們想要使用它的話,就須要建立一個本身的幫助類去繼承它。 SQLiteOpenHelper中有兩個抽象方法,分別是onCreate()和onUpgrade(),咱們必須在本身的幫助類裏面重寫這兩個方法,而後分別在這兩個方法中去實現建立、升級數據庫的邏輯。SQLiteOpenHelper 中 還 有 兩 個 非 常 重 要 的 實 例方 法 , getReadableDatabase() 和getWritableDatabase()。這兩個方法均可以建立或打開一個現有的數據庫(若是數據庫已存在則直接打開,不然建立一個新的數據庫),並返回一個可對數據庫進行讀寫操做的對象。不一樣的是,當數據庫不可寫入的時候(如磁盤空間已滿) getReadableDatabase()方法返回的對象將以只讀的方式去打開數據庫,而getWritableDatabase()方法則將出現異常。SQLiteOpenHelper中有兩個構造方法可供重寫,通常使用參數少一點的那個構造方法便可。java
這個構造方法中接收四個參數,android
第一個參數是Context,這個沒什麼好說的,必需要有它才能對數據庫進行操做。sql
第二個參數是數據庫名,建立數據庫時使用的就是這個指定的名稱。shell
第三個參數容許咱們在查詢數據的時候返回一個自定義的Cursor,通常都是傳回null。數據庫
第四個參數表示當前數據庫的版本號, 可用於對數據庫進行升級操做。app
構建出SQLiteOpenHelper的實例以後,再調用它的getReadableDatabase()或getWritableDatabase()方法就可以建立數據庫了,數據庫文件會存放在/data/data/<package name>/databases/目錄下。此時, 重寫的onCreate()方法也會得
到執行, 因此一般會在這裏去處理一些建立表的邏輯。ide
---------下面用一個實例來講明吧------------------------------------測試
MyDatabaseHelper.java的代碼以下:this
package yaowen.com.filepersistencetest; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.widget.Toast; /** * Created by YAOWEN on 2015/9/17. */ public class MyDatabaseHelper extends SQLiteOpenHelper { public static final String CREATE_BOOK = "create table book (" + "id integer primary key autoincrement, " + "author text, " + "price real, " + "pages integer, " + "name text)"; public static final String CREATE_CATEGORY = "create table Category(" + "id integer primary key autoincrement," + "category_name text," + "category_code integer)"; private Context mContext; public MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); mContext = context; } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_BOOK); db.execSQL(CREATE_CATEGORY); Toast.makeText(mContext, "建立book數據表成功!", Toast.LENGTH_SHORT).show(); Toast.makeText(mContext, "建立Category表成功!", Toast.LENGTH_SHORT).show(); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("drop table if exists book"); db.execSQL("drop table if exists Category"); onCreate(db); } }
MainActivity.java的代碼以下:spa
package yaowen.com.filepersistencetest; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { private MyDatabaseHelper dbHelper; private Button createDatabase, add_data, update_btn, delete_btn, query_btn, replace_btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //實例化一個dbHelper對象 dbHelper = new MyDatabaseHelper(this, "BookStore.db", null, 3); //初始化UI控件 createDatabase = (Button) findViewById(R.id.create_database); add_data = (Button) findViewById(R.id.add_data); update_btn = (Button) findViewById(R.id.update_data); delete_btn = (Button) findViewById(R.id.delete_data); query_btn = (Button) findViewById(R.id.query_data); replace_btn= (Button) findViewById(R.id.replace_data); //按鈕createDatabase的監聽響應事件 createDatabase.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dbHelper.getWritableDatabase(); } }); //添加數據表數據 add_data.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); //開始組裝第一條數據 values.put("name", "The Yaowen Code"); values.put("author", "YaoWen"); values.put("pages", "454"); values.put("price", "19.50"); //插入第一條數據 db.insert("book", null, values); //開始組裝第二條數據 values.put("name", "The Siny Code"); values.put("author", "Siny"); values.put("pages", "459"); values.put("price", "39.50"); //插入第二條數據 db.insert("book", null, values); //開始組裝第三條數據 values.put("name", "The HTML5 Code"); values.put("author", "Siny"); values.put("pages", "678"); values.put("price", "59.50"); //插入第三條數據 db.insert("book", null, values); //開始組裝第四條數據 values.put("name", "The C# Code"); values.put("author", "HelloWorld"); values.put("pages", "897"); values.put("price", "29.50"); //插入第四條數據 db.insert("book", null, values); } }); //更新數據表數據 update_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues contentValues = new ContentValues(); //更新第一條數據 contentValues.put("name", "The Java Code"); db.update("book", contentValues, "author=?", new String[]{ "Siny" }); //更新第二條數據 contentValues.put("name", "The Android Code"); db.update("book", contentValues, "author=?", new String[]{ "YaoWen" }); } }); //刪除數據表數據 delete_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SQLiteDatabase database = dbHelper.getWritableDatabase(); database.delete("book", "pages>?", new String[]{"500"}); } }); //查詢數據表數據 query_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SQLiteDatabase database = dbHelper.getWritableDatabase(); //查詢book數據表裏的全部數據; Cursor cursor = database.query("book", null, null, null, null, null, null); if (cursor.moveToFirst()) { do { //遍歷Cursor對象,取出數據並打印 String name = cursor.getString(cursor.getColumnIndex("name")); String author = cursor.getString(cursor.getColumnIndex("author")); int pages = cursor.getInt(cursor.getColumnIndex("pages")); double price = cursor.getDouble(cursor.getColumnIndex("price")); Log.d("MyLog","--------------------"); Log.d("MyLog","書名是:"+name); Log.d("MyLog","做者是:"+author); Log.d("MyLog","編號是:"+pages); Log.d("MyLog","價格是:"+price); Log.d("MyLog","--------------------"); }while (cursor.moveToNext()); } cursor.close(); } }); //測試數據庫的事務功能 replace_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SQLiteDatabase database = dbHelper.getWritableDatabase(); database.beginTransaction();//開啓事務 try { database.delete("book", null, null); if (true) { //這裏拋出一個異常,讓事務失敗 throw new NullPointerException(); } ContentValues contentValues = new ContentValues(); contentValues.put("name", "Game of Thrones"); contentValues.put("author", "HelloWorld"); contentValues.put("pages", 720); contentValues.put("price", 21.85); }catch (Exception e){ e.printStackTrace(); }finally { database.endTransaction();//結束事務 } } }); } }
main_activity.xml的代碼入下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:id="@+id/create_database" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="建立數據庫" /> <Button android:id="@+id/add_data" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="添加數據" /> <Button android:id="@+id/update_data" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="更新數據" /> <Button android:id="@+id/delete_data" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="刪除數據" /> <Button android:id="@+id/query_data" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="查詢數據" /> <Button android:id="@+id/replace_data" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="替換數據(事務)" /> </LinearLayout>
下面是程序運行效果圖了:
下面是程序運行是調試語句,也就是程序成功運行了!
下面是shell命令查詢的數據:(具體怎麼用shell命令,自行百度了吧)