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

Android 資料庫增刪改查:execSQL 與 API 兩種寫法對比

編輯:關於 Android 開發

Android 資料庫增刪改查:execSQL 與 API 兩種寫法對比


這篇示範 SQLite 增刪改查的第一種寫法:直接用手寫 SQL 語句搭配 execSQL() 做增刪改,用 rawQuery() 做查詢。

MainActivity 在 onCreate 中初始化資料庫,並為四顆按鈕掛上點擊事件:

package com.itheima.crud;

import android.app.Activity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import com.itheima.crud.bean.InfoBean;
import com.itheima.crud.dao.InfoDao;

public class MainActivity extends Activity implements OnClickListener {
    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;

        // 創建一個幫助類對象
        MySqliteOpenHelper mySqliteOpenHelper = new MySqliteOpenHelper(mContext);
        // 調用 getReadableDatabase 方法,初始化數據庫的創建
        SQLiteDatabase db = mySqliteOpenHelper.getReadableDatabase();

        findViewById(R.id.bt_add).setOnClickListener(this);
        findViewById(R.id.bt_del).setOnClickListener(this);
        findViewById(R.id.bt_update).setOnClickListener(this);
        findViewById(R.id.bt_query).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        InfoDao infoDao = new InfoDao(mContext);
        switch (v.getId()) {
            case R.id.bt_add:
                InfoBean bean = new InfoBean();
                bean.name = "張三";
                bean.phone = "110";
                infoDao.add(bean);
                InfoBean bean1 = new InfoBean();
                bean1.name = "李四";
                bean1.phone = "120";
                infoDao.add(bean1);
                break;
            case R.id.bt_del:
                infoDao.del("張三");
                break;
            case R.id.bt_update:
                InfoBean bean2 = new InfoBean();
                bean2.name = "張三";
                bean2.phone = "119";
                infoDao.update(bean2);
                break;
            case R.id.bt_query:
                infoDao.query("張三");
                infoDao.query("李四");
                break;
            default:
                break;
        }
    }
}

幫助類 MySqliteOpenHelper 負責建表:

package com.itheima.crud;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MySqliteOpenHelper extends SQLiteOpenHelper {
    public MySqliteOpenHelper(Context context) {
        super(context, "info.db", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table info (_id integer primary key autoincrement, name varchar(20), phone varchar(11))");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // db.execSQL("alter table info add phone varchar(11)");
    }
}

資料模型 InfoBean:

package com.itheima.crud.bean;

public class InfoBean {
    public String id;
    public String name;
    public String phone;
}

核心的 DAO 層,把增刪改查四個操作各自封裝:

package com.itheima.crud.dao;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.itheima.crud.MySqliteOpenHelper;
import com.itheima.crud.bean.InfoBean;

public class InfoDao {
    private MySqliteOpenHelper mySqliteOpenHelper;

    public InfoDao(Context context) {
        mySqliteOpenHelper = new MySqliteOpenHelper(context);
    }

    public void add(InfoBean bean) {
        SQLiteDatabase db = mySqliteOpenHelper.getWritableDatabase();
        // sql: sql 語句, bindArgs: 占位符的值
        db.execSQL("insert into info(name,phone) values(?,?);",
                new Object[]{bean.name, bean.phone});
        db.close();
    }

    public void del(String name) {
        SQLiteDatabase db = mySqliteOpenHelper.getReadableDatabase();
        db.execSQL("delete from info where name=?;", new Object[]{name});
        db.close();
    }

    public void update(InfoBean bean) {
        SQLiteDatabase db = mySqliteOpenHelper.getReadableDatabase();
        db.execSQL("update info set phone=? where name=?;",
                new Object[]{bean.phone, bean.name});
        db.close();
    }

    public void query(String name) {
        SQLiteDatabase db = mySqliteOpenHelper.getReadableDatabase();
        // selectionArgs: 查詢條件占位符的值,返回一個 cursor 對象
        Cursor cursor = db.rawQuery(
                "select _id, name, phone from info where name = ?;", new String[]{name});
        // 解析 Cursor 中的數據
        if (cursor != null && cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                int id = cursor.getInt(0);
                String name_str = cursor.getString(1);
                String phone = cursor.getString(2);
                System.out.println("_id:" + id + ";name:" + name_str + ";phone:" + phone);
            }
            cursor.close();
        }
        db.close();
    }
}

四顆按鈕的布局:

<?xml version="1.0"?>
<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <Button android:id="@+id/bt_add" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="@string/add" />
    <Button android:id="@+id/bt_del" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="@string/del" />
    <Button android:id="@+id/bt_update" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="@string/update" />
    <Button android:id="@+id/bt_query" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="@string/query" />
</LinearLayout>

這種寫法的特點與取捨:

優點是直接、SQL 一目了然。缺點也很明顯——增刪改沒有回傳值,無法判斷 SQL 是否執行成功;而且 SQL 語句全靠手寫,容易出錯(少個分號、欄位名打錯都不會在編譯期報錯)。

因此實務上更常改用 insert / delete / update / query 這組 API:它們會回傳受影響的行數或新 id,能明確判斷操作成敗,也不必自己拼 SQL,是更安全的選擇。

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