开发者

Disallow duplicate records and check if database is available

开发者 https://www.devze.com 2023-04-03 09:08 出处:网络
I am creating a database and I\'m inserting a row like so: /* Add two DataSets to the Table. */ myDB.execSQL(\"INSERT INTO \"

I am creating a database and I'm inserting a row like so:

/* Add two DataSets to the Table. */
myDB.execSQL("INSERT INTO "
              + MY_DATABASE_TABLE
              + " (LastName, FirstName, Country, Age)"
              + " VALUES ('Gramlich', 'Nicolas', 'Germany', 20);");
 myDB.execSQL("INSERT INTO "
              + MY_DATABASE_TABLE
              + " (LastName, FirstName, Country, Age)"
              + " VALUES ('Doe', 'John', 'US', 34);");

I have two questions regarding the above code:

  1. How do I disallow duplicate records? I want to check incoming data at the insert time. How can I achieve that? Should I use IF NOT EXISTS?

  2. How can I check whether that dat开发者_如何学Pythonabase is available or not? So far, without any success, I've tried:

    private static String DB_PATH = "/data/data/YOUR_PACKAGE/databases/myDBName";
    private static String DB_NAME = "myDBName";
    
    private boolean checkDataBase() {
        SQLiteDatabase checkDB = null;
        try {
            checkDB = SQLiteDatabase.openDatabase(DB_PATH, null,
            SQLiteDatabase.OPEN_READONLY);
            checkDB.close();
        } catch (SQLiteException e) {
            // database doesn't exist yet.
        }
        return checkDB != null ? true : false;
    }
    

Any suggestions on how to achieve this?


to prevent duplicates create a UNIQUE INDEX on that table.

At runtime, you have at least two options:

  1. let the index give you an exception if you attempt a duplicate, then catch that exception and do something else, or

  2. Query the table pro-actively to see if the new record exists, and if you find it you know there is a duplicate, so do something else.


Here are a few suggestions:

  1. When creating your tables, define the columns that you want to prevent duplicates as UNIQUE.
  2. Your checkDataBase() method is a bit strange. Have you considered using the SQLiteOpenHelper class in your implementation to simplify things?

http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号