SQLiteDatabase仅在尚未添加的情况下添加

时间:2015-10-02 13:32:00

标签: java android database android-sqlite

我正在实施“添加到收藏夹”功能。用户应该能够将数据添加到数据库。

DatabaseHandler正在运行,我已经创建了一个类来处理get / set方法。

我可以轻松地将数据添加到数据库中,但是我无法弄清楚如何检查特定的ID是否已经存在,从而不会向数据库添加副本。

这是我的DatabaseHandler:

public class DatabaseHandler extends SQLiteOpenHelper {

// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "favoriteMovies";

// DataFavorites table name
private static final String TABLE_NAME = "movies";

// DataFavorites Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_URL = "url";
private static final String KEY_RELEASEDATE = "releaseDate";


public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {

    String CREATE_DATAFAVORITES_TABLE = "CREATE TABLE " + TABLE_NAME + "("
            + KEY_ID + "  INTEGER PRIMARY KEY," + KEY_TITLE + " TEXT,"
            + KEY_URL + " TEXT,"+ KEY_RELEASEDATE + " TEXT" + ")";
    db.execSQL(CREATE_DATAFAVORITES_TABLE);



}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);

    // Create tables again
    onCreate(db);

}


// Adding new movie
public void addMovie(DataFavorites movie) {

    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_ID, movie.getId()); // movie id
    values.put(KEY_TITLE, movie.getTitle()); // movie title
    values.put(KEY_URL, movie.getUrl()); // movie url (poster)
    values.put(KEY_RELEASEDATE, movie.getReleaseDate()); // movie url (poster)

    // Inserting Row
    db.insert(TABLE_NAME, null, values);
    db.close(); // Closing database connection

}

// Getting single movie
public DataFavorites getMovie(int id) {

    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(TABLE_NAME, new String[] { KEY_ID,
                    KEY_TITLE, KEY_URL, KEY_RELEASEDATE }, KEY_ID + "=?",
            new String[] { String.valueOf(id) }, null, null, null, null);
    if (cursor != null)
        cursor.moveToFirst();

    DataFavorites movie = new DataFavorites(Integer.parseInt(cursor.getString(0)),
            cursor.getString(1), cursor.getString(2), cursor.getString(3));
    // return movie
    return movie;

}

// Getting All movie
public List<DataFavorites> getAllMovie() {

    List<DataFavorites> movieList = new ArrayList<DataFavorites>();
    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_NAME;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            DataFavorites dataFavorites = new DataFavorites();

            dataFavorites.setId(Integer.parseInt(cursor.getString(0)));
            dataFavorites.setTitle(cursor.getString(1));
            dataFavorites.setUrl(cursor.getString(2));
            dataFavorites.setReleaseDate(cursor.getString(3));

            // Adding movie to list
            movieList.add(dataFavorites);
        } while (cursor.moveToNext());
    }

    // return movie list
    return movieList;

}

// Getting movie Count
public int getMoviesCount(){

    String countQuery = "SELECT  * FROM " + TABLE_NAME;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    cursor.close();

    // return count
    return cursor.getCount();

}

// Updating single movie
public int updateMovie(DataFavorites movie) {

    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_ID, movie.getId());
    values.put(KEY_TITLE, movie.getTitle());
    values.put(KEY_URL, movie.getUrl());
    values.put(KEY_RELEASEDATE, movie.getReleaseDate());

    // updating row
    return db.update(TABLE_NAME, values, KEY_ID + " = ?",
            new String[] { String.valueOf(movie.getId()) });

}

// Deleting single movie
public void deleteMovie(DataFavorites movie) {

    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_NAME, KEY_ID + " = ?",
            new String[] { String.valueOf(movie.getId()) });
    db.close();

}

在这里,如果id尚不存在,我想添加数据:

public void AddToFavorites(MenuItem item) {

    DatabaseHandler db = new DatabaseHandler(this);

    /* if ( id is not there ){

    // Inserting movie
    Log.d("Insert: ", "Inserting movie..");
    db.addMovie(new DataFavorites(Integer.parseInt(Id), Title, Poster, Release));
} */

}

2 个答案:

答案 0 :(得分:2)

在“表”列中添加UNIQUE索引以防止重复输入。另请注意,如果插入重复,它将抛出异常,因此不要忘记处理

答案 1 :(得分:0)

你应该使用:

db.execSql("INSERT OR IGNORE INTO movies (columns names) VALUES (your values)");

db.execSql("INSERT OR REPLACE INTO movies (columns names) VALUES (your values)");

插入值,如果它们已经在表中,则不会添加它们(第一种方法)或者它们将被替换(第二种方法)。