IT박스

Android의 SQLite 특정 행을 업데이트하는 방법

itboxs 2020. 6. 30. 20:58
반응형

Android의 SQLite 특정 행을 업데이트하는 방법


한동안 특정 행을 업데이트하려고 시도했지만 두 가지 방법이 있습니다. 내가 읽고 시도한 것에서 다음을 사용할 수 있습니다.

execSQL(String sql) 방법

아니면 그:

update(String table, ContentValues values, String whereClause, String[] whereArgs) 방법.

(안드로이드를 처음 사용하고 SQL을 처음 접했을 때 이것이 잘못된 지 알려주세요.)

실제 코드를 보도록하겠습니다.

myDB.update(TableName, "(Field1, Field2, Field3)" + " VALUES ('Bob', 19, 'Male')", "where _id = 1", null);

나는 이것을 달성하려고 노력하고있다 :

기본 키 (_id)가 1 인 Field1, Field2 및 Field3을 업데이트하십시오.

Eclipse는 "update"라는 단어 바로 아래에 빨간색 선을 표시하고 다음과 같은 설명을 제공합니다.

SQLiteDatabase 유형의 update (String, ContentValues, String, String []) 메소드는 인수 (String, String, String, null)에 적용 할 수 없습니다.

ContentValues를 올바르게 할당하지 않은 것 같습니다. 누구든지 올바른 방향으로 나를 가리킬 수 있습니까?


먼저 ContentValues ​​객체를 만듭니다.

ContentValues cv = new ContentValues();
cv.put("Field1","Bob"); //These Fields should be your String values of actual column names
cv.put("Field2","19");
cv.put("Field2","Male");

그런 다음 업데이트 방법을 사용하면 이제 작동합니다.

myDB.update(TableName, cv, "_id="+id, null);

간단한 방법 :

String strSQL = "UPDATE myTable SET Column1 = someValue WHERE columnId = "+ someValue;

myDataBase.execSQL(strSQL);

먼저 ContentValues 객체를 만듭니다.

ContentValues cv = new ContentValues();
cv.put("Field1","Bob");
cv.put("Field2","19");

그런 다음 업데이트 방법을 사용하십시오. 세 번째 인수는 where 절입니다. "?" 자리 표시 자입니다. 네 번째 인수 (id)로 대체됩니다.

myDB.update(MY_TABLE_NAME, cv, "_id = ?", new String[]{id});

특정 행을 업데이트하는 가장 깨끗한 솔루션입니다.


  1. 개인적으로 편의를 위해 .update를 선호합니다. 그러나 execsql은 동일하게 작동합니다.
  2. 당신은 문제가 당신의 콘텐츠 가치라는 추측에 옳습니다. ContentValue 오브젝트를 작성하고 데이터베이스 행의 값을 거기에 두어야합니다.

이 코드는 예제를 수정해야합니다.

 ContentValues data=new ContentValues();
 data.put("Field1","bob");
 data.put("Field2",19);
 data.put("Field3","male");
 DB.update(Tablename, data, "_id=" + id, null);

당신은 이것을 시도 할 수 있습니다 ...

db.execSQL("UPDATE DB_TABLE SET YOUR_COLUMN='newValue' WHERE id=6 ");

이 코드를 DB에서 사용하십시오`

public boolean updatedetails(long rowId,String name, String address)
      {
       ContentValues args = new ContentValues();
       args.put(KEY_ROWID, rowId);          
       args.put(KEY_NAME, name);
       args.put(KEY_ADDRESS, address);
       int i =  mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null);
    return i > 0;
     }

샘플에서 업데이트하려면 java.이 코드를 사용하십시오.

  //DB.open();

        try{
              //capture the data from UI
              String name = ((EditText)findViewById(R.id.name)).getText().toString().trim();
              String address =(EditText)findViewById(R.id.address)).getText().toString().trim();

              //open Db
              pdb.open();

              //Save into DBS
              pdb.updatedetails(RowId, name, address);
              Toast.makeText(this, "Modified Successfully", Toast.LENGTH_SHORT).show();
              pdb.close();
              startActivity(new Intent(this, sample.class));
              finish();
        }catch (Exception e) {
            Log.e(TAG_AVV, "errorrrrr !!");
            e.printStackTrace();
        }
    pdb.close();

이것이 도움이되기를 바랍니다.

public boolean updatedetails(long rowId, String address)
  {
     SQLiteDatabase mDb= this.getWritableDatabase();
   ContentValues args = new ContentValues();
   args.put(KEY_ROWID, rowId);          
   args.put(KEY_ADDRESS, address);
  return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null)>0;   
 }

SQLite 에서이 하나의 업데이트 방법을 시도하십시오.

int id;
ContentValues con = new ContentValues();
con.put(TITLE, title);
con.put(AREA, area);
con.put(DESCR, desc);
con.put(TAG, tag);
myDataBase.update(TABLE, con, KEY_ID + "=" + id,null);

이렇게 시도해보십시오 :

ContentValues values=new ContentValues();
values.put("name","aaa");
values.put("publisher","ppp");
values.put("price","111");

int id=sqdb.update("table_name",values,"bookid='5' and booktype='comic'",null);

if your sqlite row has a unique id or other equivatent, you can use where clause, like this

update .... where id = {here is your unique row id}

For updates, need to call setTransactionSuccessfull for changes to get committed like so:

db.beginTransaction();
try {
    db.update(...) 
    db.setTransactionSuccessfull(); // changes get rolled back if this not called
} finally {
   db.endTransaction(); // commit or rollback
}

//Here is some simple sample code for update

//First declare this

private DatabaseAppHelper dbhelper;
private SQLiteDatabase db;

//initialize the following

dbhelper=new DatabaseAppHelper(this);
        db=dbhelper.getWritableDatabase();

//updation code

 ContentValues values= new ContentValues();
                values.put(DatabaseAppHelper.KEY_PEDNAME, ped_name);
                values.put(DatabaseAppHelper.KEY_PEDPHONE, ped_phone);
                values.put(DatabaseAppHelper.KEY_PEDLOCATION, ped_location);
                values.put(DatabaseAppHelper.KEY_PEDEMAIL, ped_emailid);
                db.update(DatabaseAppHelper.TABLE_NAME, values,  DatabaseAppHelper.KEY_ID + "=" + ?, null);

//put ur id instead of the 'question mark' is a function in my shared preference.


 public void updateRecord(ContactModel contact) {
    database = this.getReadableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COLUMN_FIRST_NAME, contact.getFirstName());
    contentValues.put(COLUMN_LAST_NAME, contact.getLastName());
    contentValues.put(COLUMN_NUMBER,contact.getNumber());
    contentValues.put(COLUMN_BALANCE,contact.getBalance());
    database.update(TABLE_NAME, contentValues, COLUMN_ID + " = ?", new String[]{contact.getID()});
    database.close();
}

just try this way

  String strFilter = "_id=" + Id;
  ContentValues args = new ContentValues();
  args.put(KEY_TITLE, title);
  myDB.update("titles", args, strFilter, null);**

Method for updation in SQLite:

public void updateMethod(String name, String updatename){
    String query="update students set email = ? where name = ?";
    String[] selections={updatename, name};
    Cursor cursor=db.rawQuery(query, selections);
}

public long fillDataTempo(String table){
    String[] table = new String[1];
    tabela[0] = table; 
    ContentValues args = new ContentValues();
    args.put(DBOpenHelper.DATA_HORA, new Date().toString());
    args.put(DBOpenHelper.NOME_TABELA, nome_tabela);
    return db.update(DATABASE_TABLE, args, STRING + " LIKE ?" ,tabela);
}

참고URL : https://stackoverflow.com/questions/9798473/sqlite-in-android-how-to-update-a-specific-row

반응형