有时候,我们需要将在数据库中不存在数据的时候,就插入数据。存在的时候就更新数据。mqsql里面提供了相应的操作方法,但是sqlite3没有提供相应的方法。
就只能,先找;如果存在就更新,不存在就插入了;
上代码
public boolean insertOrUpdateBook(UserBookInfo userBookInfo){ SQLiteDatabase database = openDatabase(); Cursor cursor = database.query( BookInfo.TABLE_NAME, new String[]{BookInfo.COLUMN_NAME_BOOK_ID}, BookInfo.COLUMN_NAME_BOOK_ID + " = ?", new String[]{userBookInfo.getBookId() + ""}, null, null, null); ContentValues initialValues = new ContentValues(); initialValues.put(UserBook.COLUMN_NAME_BOOK_ID, userBookInfo.getBookId()); initialValues.put(UserBook.COLUMN_NAME_USER_ID, userBookInfo.getUserId()); initialValues.put(UserBook.COLUMN_NAME_READABLE, userBookInfo.getReadable()); initialValues.put(UserBook.COLUMN_NAME_STARS_COUNT, userBookInfo.getStarsCount()); initialValues.put(UserBook.COLUMN_NAME_TIME_LENGTH, userBookInfo.getTimeLength()); long result = 0; try { if (cursor != null && cursor.getCount() > 0) { //更新操作 result = database.update(UserBook.TABLE_NAME, initialValues, UserBook.COLUMN_NAME_BOOK_ID + " = ?", new String[]{userBookInfo.getBookId() + ""}); }else{ //插入操作 result = database.insert(UserBook.TABLE_NAME, null, initialValues); } } catch (Exception e) { } finally{ if (null != cursor) { cursor.close(); } closeDatabase(); } return result > 0; }