禁止重复记录并检查数据库是否可用
我正在创建一个数据库,并像这样插入一行:
/* 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);");
我对上述代码有两个问题:
如何禁止重复记录? 我想在插入时检查传入数据时间。我怎样才能做到这一点?我应该使用
IF NOT EXISTS
吗?如何检查该数据库是否可用?到目前为止,我已经尝试过,但没有成功:
private static String DB_PATH = "/data/data/YOUR_PACKAGE/databases/myDBName"; 私有静态字符串 DB_NAME = "myDBName"; 私有布尔 checkDataBase() { SQLiteDatabase checkDB = null; 尝试 { checkDB = SQLiteDatabase.openDatabase(DB_PATH, null, SQLiteDatabase.OPEN_READONLY); checkDB.close(); } catch (SQLiteException e) { // 数据库尚不存在。 } 返回 checkDB != null ?真:假; }
关于如何实现此目的有什么建议吗?
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 database 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为了防止重复,在该表上创建一个唯一索引。
在运行时,您至少有两个选择:
如果您尝试重复,让索引给您一个异常,然后捕获该异常并执行其他操作,或者
主动查询表以查看新记录是否存在,如果找到,则知道存在重复,因此执行其他操作。
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.
以下是一些建议:
http://developer.android.com/reference/android/database/sqlite /SQLiteOpenHelper.html
Here are a few suggestions:
http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html