将数据插入数据库时,我使用 -1。我是否应该使用 0 来指示是否未插入任何内容,然后返回 false。只是想知道这是正确的方法吗?
非常感谢,
标记
例程.java
if (routineInserted) {
Toast.makeText(RoutineEdit.this, "Activity Inserted", Toast.LENGTH_LONG).show();
MediaPlayer mymedia = MediaPlayer.create(RoutineEdit.this, R.raw.whoosh);
mymedia.start();
} else {
数据库.java
public boolean insertRoutine(int activityImage, String selectedDay, int activitySlot) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(RoutineColumn1,selectedDay);
contentValues.put(RoutineColumn2,activityImage);
contentValues.put(RoutineColumn3,activitySlot);
long result = db.insert(RoutineTable, null, contentValues); // The db.insert is responsible for insertion of the data into the database and stores the result of this action (either true or false) in result.
if(result == -1) // if the result is not equal to -1 or data is not successfully inserted it will return FALSE. otherwise TRUE
return false;
else
return true;}
最佳答案
根据doc .
Returns long the row ID of the newly inserted row, or -1 if an error occurred
所以你应该使用-1。
好吧,为了进一步阐述此 API 的开发人员选择 -1 作为任何发生 SQLException 的返回值。
有关更多信息,您应该查看source code
还有一件事,您可以使用一个 return 语句而不是两个。
public boolean insertRoutine(int activityImage, String selectedDay, int activitySlot) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(RoutineColumn1,selectedDay);
contentValues.put(RoutineColumn2,activityImage);
contentValues.put(RoutineColumn3,activitySlot);
long result = db.insert(RoutineTable, null, contentValues); // The db.insert is responsible for insertion of the data into the database and stores the result of this action (either true or false) in result.
return (result != -1)
}
关于java - 将数据插入数据库 - 为什么我使用 -1 而不是 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45650357/