android - 防止在SQLite中重复插入数据

时间:2018-01-25 13:12:18

标签: java android android-sqlite

我刚学会在android上使用sqlite。如何在插入时防止重复数据..那么,当有相同的数据输入时,它会覆盖数据吗?

这里我附上了代码片段:

@Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_FAVORIT_TABLE = "CREATE TABLE " + Constant.favoritDBtable + "("
                + Constant.id_postFav + " INTEGER PRIMARY KEY AUTOINCREMENT," + Constant.titleFav + " TEXT," + Constant.namaPerusahaanFav + " TEXT,"
                + Constant.lokasiFav + " TEXT," + Constant.kriteria_1Fav + " TEXT," + Constant.kriteria_2Fav
                + " TEXT," + Constant.kriteria_3Fav + " TEXT," + Constant.gajiFav + " TEXT," + Constant.img_logoFav
                + " TEXT," + Constant.tanggalFav + " TEXT);";

public String addFavorit(Favorit favorit){
        SQLiteDatabase db = this.getWritableDatabase();
//        long rows = 0;

        ContentValues values = new ContentValues();
        values.put(Constant.titleFav, favorit.getTitleFav());
        values.put(Constant.namaPerusahaanFav, favorit.getNamaPerusahaanFav());
        values.put(Constant.lokasiFav, favorit.getLokasiFav());
        values.put(Constant.kriteria_1Fav, favorit.getKriteria_1Fav());
        values.put(Constant.kriteria_2Fav, favorit.getKriteria_2Fav());
        values.put(Constant.kriteria_3Fav, favorit.getKriteria_3Fav());
        values.put(Constant.gajiFav, favorit.getGajiFav());
        values.put(Constant.img_logoFav, favorit.getImg_logoFav());
        values.put(Constant.tanggalFav, favorit.getTanggalFav());

      db.insert(Constant.favoritDBtable, null, values,);

Log.d("Favorit saved: ", "Success 200 OK");
        return null;
    }

MainActivity.java

@Override
    public void onClick(View v) {

        if (job.getTitle() != null && job.getLokasi() != null){
        saveToFavoritDB();
        }
    }

    private void saveToFavoritDB() {
        Favorit favorit = new Favorit();

        favorit.setTitleFav(job.getTitle());
        favorit.setGajiFav(job.getGaji());

        Log.d(TAG, "gaji " + job.getGaji());

        db.addFavorit(favorit);

        List<Favorit> favList = db.getAllFavorit();

        for (Favorit each : favList) {
            String log = "ID: " + each.getTitleFav() + ", Name: " + each.getLokasiFav() + ", Phone: " + each.getGajiFav();
            Log.d(TAG, "saveToFavoritDB: " + String.valueOf(db.getCountFavorit()));
            Log.d(TAG, "Hasil: " + log);
        }
    }
希望你能帮助我

3 个答案:

答案 0 :(得分:0)

创建一个函数以检查行是否在db中

private static boolean CheckIsInDBorNot(String titleFav) {
        String selectQuery = "SELECT  * FROM " + Constant.favoritDBtable + " WHERE " + Constant.titleFav +"'"+titleFav "'";
        final SQLiteDatabase db = open();
        Cursor cursor = db.rawQuery(selectQuery, null);
        if (cursor.getCount() <= 0) {
            cursor.close();
            return false;
        }
        cursor.close();
        return true;
    }

而不是检查

if (!CheckIsInDBorNot(commentOrderId, commentId)) {
                db.insertOrThrow(Constant.favoritDBtable, null, cVal);
            }

它将检查并插入

答案 1 :(得分:0)

在通过addFavorit方法之前,您可以添加一种方法来检查数据是否已存在以防止重复。

  boolean check;

  check = checkDuplicate(...,...,...,id_post); // check whether data exists
    if(check == true)  // if exists
    {
       Toast.makeText(MainActivity.this, " Data Already Exists", Toast.LENGTH_LONG).show();
    }else{
        db.addFavorit(favorit);
  }

  public static boolean checkDuplicate(String TableName,String dbfield, String fieldValue, int id_post) {
  String Query = ".... WHERE "+ Constant.id_postFav +"="+ id_post; // your query 
  Cursor cursor = db.rawQuery(Query, null);
      if(cursor.getCount() <= 0){
      cursor.close();
      return false;
     }
      cursor.close();
      return true;
  }

答案 2 :(得分:0)

IsItemExist()课程中创建方法DatabaseHelper,并在您的活动类中调用此方法,例如IsItemExist(name,mobile)

 public boolean IsItemExist(String name,String mobile) {
    try
    {
        SQLiteDatabase db=this.getReadableDatabase();
        Cursor cursor=db.rawQuery("SELECT "+NAME+" FROM "+TABLE+" WHERE "+NAME+"=?",new String[]{name});
        Cursor cursor1=db.rawQuery("SELECT "+MOBILE+" FROM "+TABLE+" WHERE "+MOBILE+"=?",new String[]{mobile});
        if (cursor.moveToFirst() && cursor1.moveToFirst())
        {
            db.close();
            Log.d("Record  Already Exists", "Table is:"+TABLE+" ColumnName:"+NAME);
            return true;//record Exists

        }
        Log.d("New Record  ", "Table is:"+TABLE+" ColumnName:"+NAME+" Column Value:"+NAME);
        db.close();
    }
    catch(Exception errorException)
    {
        Log.d("Exception occured", "Exception occured "+errorException);
        // db.close();
    }

        return false;

}