SQLite in Android Come aggiornare una riga specifica


138

Sto provando ad aggiornare una riga specifica da un po 'di tempo e sembra che ci siano due modi per farlo. Da quello che ho letto e provato, puoi semplicemente usare:

execSQL(String sql) metodo

o il:

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

(Fammi sapere se questo non è corretto poiché sono nuovo su Android e molto nuovo su SQL.)

Quindi fammi arrivare al mio codice attuale.

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

Sto cercando di ottenere questo risultato:

Aggiorna Field1, Field2 e Field3 dove la chiave primaria (_id) è uguale a 1.

Eclipse mi dà una linea rossa proprio sotto la parola "aggiornamento" e mi dà questa spiegazione:

L'aggiornamento del metodo (String, ContentValues, String, String []) nel tipo SQLiteDatabase non è applicabile per gli argomenti (String, String, String, null)

Suppongo di non assegnare correttamente ContentValues. Qualcuno può indicarmi la giusta direzione?

Risposte:


289

Per prima cosa crea un oggetto 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");

Quindi utilizzare il metodo di aggiornamento, dovrebbe funzionare ora:

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

Eclipse mi sta dando delle sottolineature rosse su "Field1", "Field2" e "Field3". Suggerimenti?
— EGHDK,

1
scusa, pensavo fossero variabili dichiarate nel tuo codice. Mettili tra virgolette.
— Akhil

Grazie per essere il primo con la risposta corretta. Mi ha risparmiato un sacco di tempo. Molto apprezzato.
— EGHDK

2
cosa succede se desidero verificare, se quella riga esiste nella tabella o no e quindi decidere se aggiornare o inserire una riga?
— Akash Raghav,

11
In realtà è una passeggiata. Il terzo parametro di db.update () dovrebbe essere solo la clausola where e il quarto sono i valori effettivi della condizione. In questo caso, la linea dovrebbe essere: myDB.update(TableName, cv, "_id=?", new String[]{id}). SQLite riempirà automaticamente il quarto parametro nel "?" nel terzo parametro, ovvero la clausola WHERE. Se il tuo terzo parametro contiene n "?" S, il quarto parametro dovrebbe essere una stringa [] di lunghezza n
— CristianoYL

48

Modo semplice:

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

myDataBase.execSQL(strSQL);

6
Questo codice genererà IllegalArgumentException. Se si esegue una query senza ContentValues, sarebbe molto meglio evitare di utilizzare il secondo argomento. Mi piace: myDataBase.execSQL (strSQL);
— Igor V Savchenko,

l'utilizzo execSQL()per gli aggiornamenti non funzionerà. Leggi execSQL () con UPDATE non si aggiorna .
— Roshana Pitigala,

Esiste un serio rischio per la sicurezza nel fare questo perché qualcuno può passare un'istruzione SQL alla variabile 'someValue', che potrebbe alterare l'intero database. Pertanto, provare sempre a fare istruzioni preparate quando si eseguono operazioni sul database.
— Achintha Isuru,

42

Inizialmente crea un oggetto ContentValues :

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

Quindi utilizzare il metodo di aggiornamento. Nota, il terzo argomento è la clausola where. Il "?" è un segnaposto. Sarà sostituito con il quarto argomento (id)

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

Questa è la soluzione più pulita per aggiornare una riga specifica.


Il modo migliore dall'utilizzo? è salvo.
— Akash Agarwal,

1
E cosa fa quello? fare?
— alphiii,

1
L'approccio dei parametri con? è il modo migliore e più sicuro. Questa dovrebbe essere la risposta accettata. Non usare mai la concatenazione di stringhe durante la composizione di istruzioni sql!
— Grisgram,

come utilizzare quando la clausola where contiene due campi?
— Banee Ishaque K,

24
  1. Preferisco personalmente l'aggiornamento per la sua comodità. Ma execsql funzionerà allo stesso modo.
  2. Hai ragione con la tua ipotesi che il problema siano i tuoi valori di contenuto. È necessario creare un oggetto ContentValue e inserire lì i valori per la riga del database.

Questo codice dovrebbe risolvere il tuo esempio:

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

12

puoi provare questo ...

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

6

spero che questo ti possa aiutare:

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;   
 }

5

Prova questo metodo di aggiornamento in 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);

5

usa questo codice nel tuo 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;
     }

per l'aggiornamento nel tuo sample.java usa questo codice

  //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();

3

Puoi provare in questo modo:

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);

2

se la tua riga sqlite ha un ID univoco o altro equivalente, puoi usare la clausola where, come questa

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

Continuo a ricevere lo stesso errore indicato nella mia domanda. Ho modificato il terzo parametro (String whereClause) in "where _id = 1". Il cambiamento si riflette anche nella mia domanda.
— EGHDK,

2

Per gli aggiornamenti, è necessario chiamare setTransactionSuccessfull affinché le modifiche vengano impegnate in questo modo:

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

2

// Ecco un semplice codice di esempio per l'aggiornamento

// Prima di tutto dichiaralo

private DatabaseAppHelper dbhelper;
private SQLiteDatabase db;

// inizializza quanto segue

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

// codice di aggiornamento

 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);

// metti il ​​tuo id al posto del 'punto interrogativo' è una funzione nelle mie preferenze condivise.


2
 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();
}

1

prova così

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

1

Metodo per l'aggiornamento 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);
}

1
SQLiteDatabase myDB = this.getWritableDatabase();

ContentValues cv = new ContentValues();
cv.put(key1,value1);    
cv.put(key2,value2); /*All values are your updated values, here you are 
                       putting these values in a ContentValues object */
..................
..................

int val=myDB.update(TableName, cv, key_name +"=?", new String[]{value});

if(val>0)
 //Successfully Updated
else
 //Updation failed

0
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);
}

0

basta dare rowId e il tipo di dati che verranno aggiornati in ContentValues.

public void updateStatus (ID stringa, stato int) {

SQLiteDatabase db = this.getWritableDatabase ();

Dati ContentValues ​​= new ContentValues ​​();

data.put ("status", status);

db.update (TableName, data, "columnName" + "=" + id, null);

}


0

Dimostrerò con un esempio completo

Crea il tuo database in questo modo

    import android.content.Context
    import android.database.sqlite.SQLiteDatabase
    import android.database.sqlite.SQLiteOpenHelper

    class DBHelper(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {
        override fun onCreate(db: SQLiteDatabase) {
            val createProductsTable = ("CREATE TABLE " + Business.TABLE + "("
                    + Business.idKey + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
                    + Business.KEY_a + " TEXT, "
                    + Business.KEY_b + " TEXT, "
                    + Business.KEY_c + " TEXT, "
                    + Business.KEY_d + " TEXT, "
                    + Business.KEY_e + " TEXT )")
            db.execSQL(createProductsTable)
        }
        override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
            // Drop older table if existed, all data will be gone!!!
            db.execSQL("DROP TABLE IF EXISTS " + Business.TABLE)
            // Create tables again
            onCreate(db)

        }
        companion object {
            //version number to upgrade database version
            //each time if you Add, Edit table, you need to change the
            //version number.
            private val DATABASE_VERSION = 1

            // Database Name
            private val DATABASE_NAME = "business.db"
        }
    }

Quindi creare una classe per facilitare CRUD -> Crea | Leggi | Aggiorna | Elimina

class Business {
    var a: String? = null
    var b: String? = null
    var c: String? = null
    var d: String? = null
    var e: String? = null

    companion object {
        // Labels table name
        const val TABLE = "Business"
        // Labels Table Columns names
        const val rowIdKey = "_id"
        const val idKey = "id"
        const val KEY_a = "a"
        const val KEY_b = "b"
        const val KEY_c = "c"
        const val KEY_d = "d"
        const val KEY_e = "e"
    }
}

Ora arriva la magia

import android.content.ContentValues
import android.content.Context

    class SQLiteDatabaseCrud(context: Context) {
        private val dbHelper: DBHelper = DBHelper(context)

        fun updateCart(id: Int, mBusiness: Business) {
            val db = dbHelper.writableDatabase
            val valueToChange = mBusiness.e
            val values = ContentValues().apply {
                put(Business.KEY_e, valueToChange)
            }
            db.update(Business.TABLE, values, "id=$id", null)
            db.close() // Closing database connection
        }
    }

devi creare ProductsAdapter che deve restituire un CursorAdapter

Quindi in un'attività basta chiamare la funzione in questo modo

internal var cursor: Cursor? = null
internal lateinit var mProductsAdapter: ProductsAdapter

 mSQLiteDatabaseCrud = SQLiteDatabaseCrud(this)
    try {
        val mBusiness = Business()
        mProductsAdapter = ProductsAdapter(this, c = todoCursor, flags = 0)
        lstProducts.adapter = mProductsAdapter


        lstProducts.onItemClickListener = OnItemClickListener { parent, view, position, arg3 ->
                val cur = mProductsAdapter.getItem(position) as Cursor
                cur.moveToPosition(position)
                val id = cur.getInt(cur.getColumnIndexOrThrow(Business.idKey))

                mBusiness.e = "this will replace the 0 in a specific position"
                mSQLiteDatabaseCrud?.updateCart(id ,mBusiness)

            }

        cursor = dataBaseMCRUD!!.productsList
        mProductsAdapter.swapCursor(cursor)
    } catch (e: Exception) {
        Log.d("ExceptionAdapter :",""+e)
    }

inserisci qui la descrizione dell'immagine

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.