安卓開發SQLite增刪改查操作例項

瓜瓜東西發表於2014-03-26

本文講如何使用Android中內建的SQLite輕量資料庫,Android SDK中已經對其進行了封裝,使用起來相當簡單。建立類繼承SQLiteOpenHelper就可以將資料庫的建立和應用版本更新後資料庫的重建納入自動管理中。本文實現一個簡單的Sqlite資料庫,儲存人名和電話號碼。

    主Activity 類SqliteSample.java 程式碼

public class SqliteSample extends Activity {
        private DBHelper mDBHelper = null;
        private Button btCreateDb = null;
        private Button btInsertData = null;
        private Button btViewData = null;
        private Button btDelOne = null;
        private Button btClearAll = null;
        
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        btCreateDb = (Button)findViewById(R.id.Button01);
        btCreateDb.setOnClickListener(new ClickViewHandler());
        btInsertData = (Button)findViewById(R.id.Button02);
        btInsertData.setOnClickListener(new ClickViewHandler());
        btInsertData.setEnabled(false);
        btViewData = (Button)findViewById(R.id.Button03);
        btViewData.setOnClickListener(new ClickViewHandler());
        btViewData.setEnabled(false);
        btDelOne = (Button)findViewById(R.id.Button04);
        btDelOne.setOnClickListener(new ClickViewHandler());
        btDelOne.setEnabled(false);
        btClearAll = (Button)findViewById(R.id.Button05);
        btClearAll.setOnClickListener(new ClickViewHandler());
        btClearAll.setEnabled(false);
    }

    public class ClickViewHandler implements OnClickListener {
            @Override
            public void onClick(View v) {
                    if (v == btCreateDb) {
                            createDB();
                    } else if (v == btInsertData) {
                            insertSomeRecords();
                    } else if (v == btViewData) {
                            ViewRecords();
                    } else if (v == btDelOne) {
                            DelOne();
                    } else if (v == btClearAll) {
                            mDBHelper.delAllPeople();
                    }
            }
    }
    
        private void createDB() {
                String DB_NAME = "sqlitedb1";
                mDBHelper = new DBHelper(
                                SqliteSample.this, DB_NAME, null, 1);
                assert(mDBHelper != null);
                btCreateDb.setEnabled(false);
                btInsertData.setEnabled(true);
                btViewData.setEnabled(true);
                btDelOne.setEnabled(true);
        btClearAll.setEnabled(true);
        }
        private void insertSomeRecords() {
                mDBHelper.addPeople("張三", "18600000000");
                mDBHelper.addPeople("李四", "13200000000");
        mDBHelper.addPeople("王五", "13200000000");
        }
        private void ViewRecords() {
                // Make the query
                Cursor c = mDBHelper.getWritableDatabase().query(
                                DBHelper.TB_NAME,null,null,null,null,null,   
                        DBHelper.NAME + " ASC"); 
                StringBuilder sbRecords = new StringBuilder("");
                if (c.moveToFirst()) {
                        int idxID = c.getColumnIndex(DBHelper.ID);
                        int idxName = c.getColumnIndex(DBHelper.NAME);
                        int idxNumber = c.getColumnIndex(DBHelper.NUMBER1);
                        // Iterator the records
                        do {
                                sbRecords.append(c.getInt(idxID));
                                sbRecords.append(".");
                                sbRecords.append(c.getString(idxName));
                                sbRecords.append(",");
                                sbRecords.append(c.getString(idxNumber));
                                sbRecords.append("/n");
                        } while (c.moveToNext());
                }
                c.close();
                // Refresh the content of TextView
                ((TextView)(findViewById(
                                R.id.TextView01))).setText(sbRecords);
        }
        private void DelOne() {
                int id;
                Cursor c = mDBHelper.getWritableDatabase().query(
                                DBHelper.TB_NAME,null,null,null,null,null,   
                        DBHelper.NAME + " ASC");
                if (c.moveToFirst()) {
                        int idxID = c.getColumnIndex(DBHelper.ID);
                        id = c.getInt(idxID);
                        mDBHelper.delPeople(id);
                }
        }
}

    ui介面 main.xml 程式碼,主要是幾個button的放置

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <TextView android:layout_width="fill_parent"
                android:layout_height="wrap_content" android:text="@string/hello" />
        <TableRow android:id="@+id/TableRow01" android:layout_width="wrap_content" android:layout_height="wrap_content">
                <Button android:text="建立資料庫" android:id="@+id/Button01"
                        android:height="30px" android:layout_width="wrap_content"
                        android:layout_height="wrap_content" />
                <Button android:text="插入幾條記錄" android:id="@+id/Button02"
                        android:height="30px" android:layout_width="wrap_content"
                        android:layout_height="wrap_content" />
        </TableRow>
        <TableRow android:id="@+id/TableRow01" android:layout_width="wrap_content" android:layout_height="wrap_content">
        <Button android:text="刪除一條" android:id="@+id/Button04"
                android:height="30px" android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
        <Button android:text="清除所有" android:id="@+id/Button05"
                android:height="30px" android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
        </TableRow>
        <Button android:text="檢視記錄" android:id="@+id/Button03"
                android:height="30px" android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:layout_gravity="center"/>
        <TextView android:text="..." android:id="@+id/TextView01"
                android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

    資料庫操作類 DBHelper.java 程式碼:

package jtapp.sqlitesamples;

public class DBHelper extends SQLiteOpenHelper {   
    
    public static final String TB_NAME = "people";   
    public static final String ID = "_id";   
    public static final String NAME = "name";   
    public static final String NUMBER1 = "number1";   
    
    public DBHelper(Context context, String name,    
            CursorFactory factory, int version) {   
        super(context, name, factory, version);
        this.getWritableDatabase();  
    }
    
    /**
     * should be invoke when you never use DBhelper
     * To release the database and etc.
     */
    public void Close() {
            this.getWritableDatabase().close();
    }
  
    public void onCreate(SQLiteDatabase db) {   
        db.execSQL("CREATE TABLE IF NOT EXISTS "    
                + TB_NAME + " ("    
                + ID + " INTEGER PRIMARY KEY,"    
                + NAME + " VARCHAR,"  
                + NUMBER1 + " VARCHAR)");   
    }   
  
    public void onUpgrade(SQLiteDatabase db,    
            int oldVersion, int newVersion) {   
        db.execSQL("DROP TABLE IF EXISTS "+TB_NAME);   
        onCreate(db);   
    }
    
    public void addPeople(String name, String number) {
            ContentValues values = new ContentValues();   
        values.put(DBHelper.NAME, name);   
        values.put(DBHelper.NUMBER1, number);   
        this.getWritableDatabase().insert(
                        DBHelper.TB_NAME, DBHelper.ID, values);  
    }
    
    public void delPeople(int id) {
        this.getWritableDatabase().delete(
                        DBHelper.TB_NAME, this.ID + " = " + id, null);
    }
    
    public void delAllPeople() {
        this.getWritableDatabase().delete(
                        DBHelper.TB_NAME, null, null);
    }
}  

    本文主要以例子的方式展示了安卓開發中SQLite的增啥改查的使用,本文提供一個SQLite增刪改查的DBHelper類,主要用來操作SQLite資料庫,讀者可以自己複製該類的程式碼使用,感謝閱讀本文

 

相關文章