1. 程式人生 > >android sqlite 完全用replace替代 insert 和 update 操作

android sqlite 完全用replace替代 insert 和 update 操作

  • android 中 sqlite資料庫相信大家或多或少都使用過。我也一樣。之前只知道 insert,update,query,delete並不知道有replace
  • 不清楚replace()的,可以看下這個來自部落格園,和這個。這兩篇都講了replace()方法的使用。但是,並不是很詳細。

  • 特別是,他們都沒有強調,如果要使用replace,一定要有一個primary key,並且,該欄位,是唯一區分到底是應該被update還是應該被insert的條件。

打個比方:如果你的資料庫中,只有兩個欄位 nameage 。而且,你是使用name作為primarykey的。那麼。第一次,你表中沒有任何的資料,呼叫replace("張三","22");

那麼就向你的表中插入了這條記錄。然後,你再次呼叫replace("張三","22");這時候,你表中的資料不變。過了一會,你呼叫replace("張三","29");,那麼,你的表中,依然是一條記錄。只不過age欄位變成29了而已。過了一會,你呼叫replace("Tom",32);。那麼,你的表中就有兩條記錄了。分別是:張三,29 和 Tom,32。

為了避免產生誤導,我說明一下replace()方法的api不是這樣使用的,我這麼寫,是為了更容易理解。

  • 下面,我給出我寫的一個DbHelper和一個DbDao。裡面有replace()方法的實際使用方式。
    • SQLiteOpenHelper .java

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

import com.apkfuns.logutils.LogUtils;

class LockDbHelper extends SQLiteOpenHelper {
    // If you change the database schema, you must increment the database version.
    private
static final int DATABASE_VERSION = 1+1+1+1; private static final String DATABASE_NAME = "lockAppSet.db"; private static final String TEXT_TYPE = " TEXT"; private static final String INTEGER_TYPE = " INTEGER"; private static final String COMMA_SEP = ","; public static final String PRIMARY_KEY = " PRIMARY KEY"; private static final String SQL_CREATE_ENTRIES = // id + title + content + date "CREATE TABLE IF NOT EXISTS " + LockColumns.TABLE_NAME + " (" + /*LockColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +*/ LockColumns.COLUMN_PACKAGE_NAME + TEXT_TYPE + PRIMARY_KEY + COMMA_SEP + LockColumns.COLUMN_IS_LOCKED + INTEGER_TYPE + " )"; private static final String SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS " + LockColumns.TABLE_NAME; LockDbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } public void onCreate(SQLiteDatabase db) { LogUtils.e("create table SQL = " + SQL_CREATE_ENTRIES); db.execSQL(SQL_CREATE_ENTRIES); } public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // This database is only a cache for online data, so its upgrade policy is // to simply to discard the data and start over db.execSQL(SQL_DELETE_ENTRIES); onCreate(db); } public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { onUpgrade(db, oldVersion, newVersion); } }
* 欄位常量
final class LockColumns {
    // To prevent someone from accidentally instantiating the contract class,
    // make the constructor private.
    private LockColumns() {
    }

    static final String TABLE_NAME = "appLockTable"; // table name
    static final String COLUMN_PACKAGE_NAME = "package_name"; //
    static final String COLUMN_IS_LOCKED = "locked"; // is locked 1,locked 0 unlocked
}
  • Dao.java

public class LockDao {

    /**
     * insert
     *
     * @param c    context
     * @param info domain
     * @return row
     */
    public static long replace(@NonNull Context c, @NonNull LockInfo info) {
        // Gets the data repository in write mode
        LockDbHelper mDbHelper = new LockDbHelper(c);
        SQLiteDatabase db = mDbHelper.getWritableDatabase();
        //noinspection TryFinallyCanBeTryWithResources
        try {
            // Create a new map of values, where column names are the keys
            ContentValues values = new ContentValues();
            values.put(LockColumns.COLUMN_PACKAGE_NAME, info.packageName);
            values.put(LockColumns.COLUMN_IS_LOCKED, info.locked);
            // Insert the new row, returning the primary key value of the new row
            long replace = db.replace(LockColumns.TABLE_NAME, null, values);
            LogUtils.e("replace = " + replace);
            return replace;
        } finally {
            db.close();
            mDbHelper.close();
        }
    }

    /**
     * insert
     *
     * @param c    context
     * @param info domain
     * @return row
     */
    public static long insert(@NonNull Context c, @NonNull LockInfo info) {
        // Gets the data repository in write mode
        LockDbHelper mDbHelper = new LockDbHelper(c);
        SQLiteDatabase db = mDbHelper.getWritableDatabase();
        //noinspection TryFinallyCanBeTryWithResources
        try {
            // Create a new map of values, where column names are the keys
            ContentValues values = new ContentValues();
            values.put(LockColumns.COLUMN_PACKAGE_NAME, info.packageName);
            values.put(LockColumns.COLUMN_IS_LOCKED, info.locked);
            // Insert the new row, returning the primary key value of the new row
            return db.insert(LockColumns.TABLE_NAME, null, values);
        } finally {
            db.close();
            mDbHelper.close();
        }
    }

    /**
     * insert
     *
     * @param c        context
     * @param dataList list of LockInfo
     * @return boolean
     */
    public static boolean insert(@NonNull Context c, @NonNull List<LockInfo> dataList) {
        // Gets the data repository in write mode
        LockDbHelper mDbHelper = new LockDbHelper(c);
        SQLiteDatabase db = mDbHelper.getWritableDatabase();
        //noinspection TryFinallyCanBeTryWithResources
        try {
            long all = 0;
            for (LockInfo info : dataList) {
                // Create a new map of values, where column names are the keys
                ContentValues values = new ContentValues();
                values.put(LockColumns.COLUMN_PACKAGE_NAME, info.packageName);
                values.put(LockColumns.COLUMN_IS_LOCKED, info.locked);
                // Insert the new row, returning the primary key value of the new row
                all += db.insert(LockColumns.TABLE_NAME, null, values) > 0 ? 1 : 0;
            }
            LogUtils.e("insert size = " + dataList.size() + " , all = " + all);
            return all == dataList.size();
        } finally {
            db.close();
            mDbHelper.close();
        }
    }


    /**
     * delete one
     *
     * @param c           context
     * @param packageName packageName
     * @return row
     */
    public static int delete(@NonNull Context c, @NonNull String packageName) {
        LockDbHelper mDbHelper = new LockDbHelper(c);
        SQLiteDatabase db = mDbHelper.getReadableDatabase();
        // noinspection TryFinallyCanBeTryWithResources
        try {
            // Define 'where' part of query.
            String selection = LockColumns.COLUMN_PACKAGE_NAME + " = ?";
            // Specify arguments in placeholder order.
            String[] selectionArgs = {packageName};
            // Issue SQL statement.
            return db.delete(LockColumns.TABLE_NAME, selection, selectionArgs);
        } finally {
            db.close();
            mDbHelper.close();
        }
    }
}
  • 其實還應該有一些其他的包,不然執行會直接報錯的。但是這裡放上這些,主要是演示一下db.replace()方法的實際用法。