在SQLite数据库表中存储重复记录

时间:2015-03-23 12:59:55

标签: android sqlite

我将数据存储到SQLite表中,如果数据已经存在,那么更新它,我能够做到这一点,但每当我更新现有记录时,它都会保存该记录的另一个副本......

DatabaseDataHelper.java: -

public class DatabaseDataHelper extends SQLiteOpenHelper {

    // Database Version
    private static final int DATABASE_VERSION = 1;
    // Database Name
    private static final String DATABASE_NAME = "Data";
    // Table Name
    private static final String TABLE_MEMBER = "Data";

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

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL("CREATE TABLE " + TABLE_MEMBER + 
                  "(Name VARCHAR(50) UNIQUE,"
                  " Title VARCHAR(50))");

        Log.d("CREATE TABLE","Create Table Successfully - classs");
    }

    public long InsertData(String strName, String strTitle) {

        try {
            SQLiteDatabase db;
            db = this.getWritableDatabase();

            ContentValues Val = new ContentValues();
            Val.put("Name", strName); 
            Val.put("Title", strTitle);

            long rows = db.insert(TABLE_MEMBER, null, Val);

            db.close();
            return rows;

        } catch (Exception e) {
            return -1;
        }
    }

    public long UpdateData(String strName, String strTitle) {

        try {
            SQLiteDatabase db;
            db = this.getWritableDatabase();

            ContentValues Val = new ContentValues();
            Val.put("Title", strTitle);

            long rows = db.update(TABLE_MEMBER, Val, "Name=?",
                    new String[] { String.valueOf(strName) });

            db.close();
            return rows;

        } catch (Exception e) {
            return -1;
        }   
    }

    public String[] SelectData(String strName) {

        try {
            String arrData[] = null;    

             SQLiteDatabase db;
             db = this.getReadableDatabase();

             Cursor cursor = db.query(TABLE_MEMBER, new String[] { "*" }, 
                     "Name=?",
                     new String[] { String.valueOf(strName) }, null, null, null, null);

                if(cursor != null) {
                    if (cursor.moveToFirst()) {
                        arrData = new String[cursor.getColumnCount()];
                        arrData[0] = cursor.getString(0);
                        arrData[1] = cursor.getString(1);
                    }
                }
                cursor.close();
                db.close();
                return arrData;
         } catch (Exception e) {
            return null;
         }
    }

    public boolean Exists(String strName) {
        SQLiteDatabase db;
        db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery("select 1 from Data where Name= ?", new String[] { strImageName });
        boolean exists = (cursor.getCount() > 0);
        cursor.close();
        return exists;
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_MEMBER);
        onCreate(db);
    }

    public Cursor getAllData() {
         String selectQuery = "Select * from "+ TABLE_MEMBER; 
         SQLiteDatabase db = this.getReadableDatabase();
         Cursor cursor = db.rawQuery(selectQuery, null);
         return cursor;
    }

}

InsertDataActivity.java: -

public boolean saveData() {
    long storeData = databaseDataHelper.InsertData(txtName.getText().toString(), editTitle.getText().toString());

    if (storeData <=  0) {
    } else
        storeData = databaseDataHelper.UpdateData(txtName.getText().toString(),
            editTitle.getText().toString());
    return true;
}

2 个答案:

答案 0 :(得分:2)

在您插入和更新数据库中的数据的InsertDataActivity中,首先插入数据,然后更新数据。这种做法是错误的。

  

您应该先更新并检查受影响的行。如果你受到0行的影响,那么只需要插入那一行。

试试以下内容:

public boolean saveData() {

    // This will Update record in the database if it is available and return row id of the updated database.
    long mNoRowsEffected = databaseDataHelper.UpdateData(txtName.getText().toString(), editTitle.getText().toString());

    // If we don't get any updated row id or if row id is null it mean the current record is not available in database 
    // so we need to insert this record to the database.
    if (mNoRowsEffected != null && mNoRowsEffected <= 0) {
        storeData = databaseDataHelper.InsertData(txtName.getText().toString(), editTitle.getText().toString());
    }

}

答案 1 :(得分:1)

编辑 - 正如SilentKiller所说,这种方法会增加数据库开销,因为我们正在进行一次额外的通话。解决此问题的推荐方法是using constraints in the SQLite database,这是更好的恕我直言。


InsertDataActivity中的{p>您正在调用InsertData(),而不检查该条目是否已存在。您应检查数据是否存在,然后相应地致电InsertData()UpdateData()

这样的事情应该有效。

  public boolean saveData() {
    String[] data = databaseDataHelper.SelectData(txtName.getText().toString());

    if (data != null) {
        storeData = databaseDataHelper.UpdateData(txtName.getText().toString(),
                editTitle.getText().toString());
    } else {
        storeData = databaseDataHelper.InsertData(txtName.getText().toString(),
                editTitle.getText().toString());
    }
}