使用database.query()在SQlite和Android中插入或更新;

Mat*_*yr' 6 sqlite android insert

有没有办法改变我的功能:

public categorie createCategoria(String categoria) {
            ContentValues values = new ContentValues();
            values.put(MySQLiteHelper.COLUMN_NOME, categoria);
            values.put(MySQLiteHelper.COLUMN_PREF, 0);

            long insertId = database.insert(MySQLiteHelper.TABLE_CATEGORIE, null,
                values);

            Cursor cursor = database.query(MySQLiteHelper.TABLE_CATEGORIE,
                allCategorieColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
                null, null, null);
            cursor.moveToFirst();
            categorie newCategoria = cursorToCategorie(cursor);
            cursor.close();
            return newCategoria;
          } 
Run Code Online (Sandbox Code Playgroud)

这是一个原始插入,我想更改此功能,使其更新或插入相应.我想改变这个因为我已经在某些地方使用了这个功能,但现在我需要选择是否插入一行或更新(或忽略插入)一行具有相同的功能COLUMN_NOME.有人可以帮我这么做吗?

我的意思是我只想插入一个新行,如果没有另一个具有相同的名称(通常你知道).

len*_*ooh 33

如果要插入或更新,可以使用insertWithOnConflict(),具体取决于记录是否存在:

SQLiteDatabase db = this.getWritableDatabase();

ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_ID, id);
contentValues.put(COLUMN_VALUE, value);

// this will insert if record is new, update otherwise
db.insertWithOnConflict(TABLE, null, contentValues, SQLiteDatabase.CONFLICT_REPLACE);
Run Code Online (Sandbox Code Playgroud)

  • 在某些情况下,"替换"不是**与"更新"相同.想象一下,如果您只想替换给定`ContentValues`中存在的那些字段.这可能发生在Web API返回部分对象的情况下(我今天自己面临这个问题). (5认同)

小智 13

您可以调用,int nRowsEffected = database.update(...);如果没有行受更新影响,则该行不存在(或者您已经冲洗了update()!)因此您需要调用database.insert(...).当然,如果nRowsEffected> 0,那么你就完成了.


ash*_*lal 8

您可以使用execSQL并使用INSERT OR REPLACE

String[] args = {"1", "newOrOldCategory"}; // where 1 is the category id
getWritableDatabase().execSQL("INSERT OR REPLACE INTO table_name (idColoumn, categoryColumn) VALUES (?, ?)", args);
Run Code Online (Sandbox Code Playgroud)

  • 小心,插入或替换可能与您对插入或更新的期望不同.请在此处查看我的回答:http://stackoverflow.com/a/4253806/365596 (3认同)