2016-01-15 69 views
1

我爲書籤/收藏夾(按鈕)創建了一個數據庫(sqlite)。 該表只有2行(id,書籤)。 每次點擊書籤按鈕,它都會在書籤列中添加相同的書籤(字符串)。如何避免Sqlite數據庫中的冗餘?

這裏是我的數據庫代碼(DatabaseHelper.java):

import android.content.ContentValues; 
import android.content.Context; 
import android.database.Cursor; 
import android.database.sqlite.SQLiteDatabase; 
import android.database.sqlite.SQLiteOpenHelper; 


public class DatabaseHelper extends SQLiteOpenHelper { 
public static final String DATABASE_NAME = "Bookmark.db"; 
public static final String TABLE_NAME = "bookmark_table"; 
public static final String COL_1 = "ID"; 
public static final String COL_2 = "BOOKMARK"; 


public DatabaseHelper(Context context) { 
    super(context, DATABASE_NAME, null, 1); 
} 

@Override 
public void onCreate(SQLiteDatabase db) { 
    db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, BOOKMARK TEXT)"); 
} 

@Override 
public void onUpgrade(SQLiteDatabase db, int i, int i2) { 
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); 
    onCreate(db); 
} 

public boolean insertData(String bookmark){ 
    SQLiteDatabase db = this.getWritableDatabase(); 
    ContentValues contentValues = new ContentValues(); 
    contentValues.put(COL_2, bookmark); 
    long result = db.insert(TABLE_NAME, null, contentValues); 
    if(result == -1) 
     return false; 
    else 
     return true; 
} 

public Cursor getAllData(){ 
    SQLiteDatabase db = this.getWritableDatabase(); 
    Cursor res = db.rawQuery("select * from " + TABLE_NAME, null); 
    return res; 
} 
} 

我怎樣才能使 「書籤」 欄目獨特之處?

回答

1

只需添加UNIQUE您的列說明後,像這樣:

db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, BOOKMARK TEXT UNIQUE)");