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:
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
?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:
let the index give you an exception if you attempt a duplicate, then catch that exception and do something else, or
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:
- When creating your tables, define the columns that you want to prevent duplicates as UNIQUE.
- 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
精彩评论