Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

SQLiteDatabase使用方法實例講解

編輯:關於 Android 程式設計

SQLite 是 Android 系統內嵌的數據庫,小巧強大,能勝任大多數 SQL 語句的處理工作,本質上就是一個文件。不過它並不像 PC 端的 MySQL 那樣功能齊全,而且 Android 不允許透過 JDBC 操作遠程數據庫,因此需要服務端數據時,只能走 WebService 與 PHP、Servlet 等後端交互。

SQLiteDatabase 類代表一個數據庫對象,所有操作都透過它完成。

打開與創建數據庫

三個靜態方法可以很方便地打開或新建數據庫:

static SQLiteDatabase openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flag);
static SQLiteDatabase openOrCreateDatabase(File file, SQLiteDatabase.CursorFactory factory);
static SQLiteDatabase openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory);

常用方法

execSQL(String sql, Object[] bindArgs) 與 execSQL(String sql) 用於執行非查詢語句;rawQuery(String sql, String[] selectionArgs) 用於查詢;beginTransaction() 與 endTransaction() 則用來包裹事務。

查詢結果以 Cursor 表示,作用類似 JDBC 中的 ResultSet,透過 move()、moveToFirst()、moveToLast()、moveToNext()、moveToPosition()、moveToPrevious() 等方法定位到需要的記錄行。

實例:鍵值對輸入與列表展示

main.xml

 <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
     xmlns:tools="https://schemas.android.com/tools"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:orientation="vertical"
     tools:context=".Main" >

     <LinearLayout
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:orientation="horizontal" >
         <TextView
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:gravity="center"
             android:text="key" />
         <EditText
             android:id="@+id/keys"
             android:layout_width="100sp"
             android:layout_height="wrap_content" />
         <TextView
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:gravity="center"
             android:text="value" />
         <EditText
             android:id="@+id/values"
             android:layout_width="100sp"
             android:layout_height="wrap_content" />
         <Button
             android:id="@+id/btn"
             android:layout_width="100sp"
             android:layout_height="wrap_content"
             android:text="submit" />
     </LinearLayout>

     <LinearLayout
         android:layout_width="match_parent"
         android:layout_height="wrap_content" >
         <ListView
             android:id="@+id/lv"
             android:layout_width="match_parent"
             android:layout_height="wrap_content" />
     </LinearLayout>
 </LinearLayout> 

填充列表用的 mytextview.xml:

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:orientation="horizontal" >
     <TextView
         android:id="@+id/listkey"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_gravity="left" />
     <TextView
         android:id="@+id/listvalue"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_marginLeft="300sp" />
 </LinearLayout> 

Main.java

這裡用 try-catch 判斷表是否存在:插入失敗就說明表還沒建,於是建表後重試。雖然能跑,但更規範的做法是先用 CREATE TABLE IF NOT EXISTS 在 onCreate 中一次性建好。

 package com.app.main;

 import android.annotation.SuppressLint;
 import android.app.Activity;
 import android.database.Cursor;
 import android.database.sqlite.SQLiteDatabase;
 import android.os.Bundle;
 import android.view.View;
 import android.view.View.OnClickListener;
 import android.widget.Button;
 import android.widget.CursorAdapter;
 import android.widget.EditText;
 import android.widget.ListView;
 import android.widget.SimpleCursorAdapter;

 public class Main extends Activity {

     EditText ed1 = null;
     EditText ed2 = null;
     Button btn = null;
     ListView lv = null;
     SQLiteDatabase db = null;

     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);

         ed1 = (EditText) this.findViewById(R.id.keys);
         ed2 = (EditText) this.findViewById(R.id.values);
         btn = (Button) this.findViewById(R.id.btn);
         lv = (ListView) this.findViewById(R.id.lv);

         db = SQLiteDatabase.openOrCreateDatabase(
                 this.getFilesDir().toString() + "/my.db3", null);

         btn.setOnClickListener(new OnClickListener() {
             @Override
             public void onClick(View view) {
                 String key = ed1.getText().toString();
                 String value = ed2.getText().toString();
                 try {
                     insertData(db, key, value);
                     Cursor cursor = db.rawQuery("select * from tb_info", null);
                     inflateListView(cursor);
                 } catch (Exception e) {
                     String sql = "create table tb_info(_id integer primary key "
                             + "autoincrement,db_key varchar(20),db_value varchar(50))";
                     db.execSQL(sql);
                     insertData(db, key, value);
                     Cursor cursor = db.rawQuery("select * from tb_info", null);
                     inflateListView(cursor);
                 }
             }
         });
     }

     /** 向數據庫中插入數據 */
     private void insertData(SQLiteDatabase db, String key, String value) {
         db.execSQL("insert into tb_info values (null,?,?)",
                 new String[]{key, value});
     }

     /** 向 ListView 中填充數據 */
     @SuppressLint("NewApi")
     public void inflateListView(Cursor cursor) {
         SimpleCursorAdapter adapter = new SimpleCursorAdapter(Main.this,
                 R.layout.mytextview, cursor,
                 new String[]{"db_key", "db_value"},
                 new int[]{R.id.listkey, R.id.listvalue},
                 CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
         lv.setAdapter(adapter);
     }

     @Override
     protected void onDestroy() {
         super.onDestroy();
         if (db != null && db.isOpen()) {
             db.close();
         }
     }
 }

效果如下:

這裡有一個容易踩的坑需要特別指出:用 SimpleCursorAdapter 封裝 Cursor 時,要求底層表的主鍵列名必須是 _id,因為 SimpleCursorAdapter 只認這個列名。範例中把 _id integer primary key autoincrement 寫進建表語句,正是為了這個原因。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved