簡體   English   中英

Android 中的 SQLite 如何更新特定行

[英]SQLite in Android How to update a specific row

一段時間以來,我一直在嘗試更新特定行,似乎有兩種方法可以做到這一點。 根據我閱讀和嘗試的內容,您可以使用:

execSQL(String sql)方法

或者:

update(String table, ContentValues values, String whereClause, String[] whereArgs)方法。

(讓我知道這是否不正確,因為我是 android 新手並且對 SQL 非常陌生。)

所以讓我來看看我的實際代碼。

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

我正在努力實現這一目標:

更新 Field1、Field2 和 Field3,其中主鍵 (_id) 等於 1。

Eclipse 在“更新”這個詞的正下方給了我一條紅線,並給了我這樣的解釋:

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 = ?", new String[]{id});

簡單的方法:

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

希望這會幫助你:

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

在您的數據庫中使用此代碼`

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

要在您的 sample.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();

可以這樣試試:

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

對於更新,需要調用 setTransactionSuccessfull 以使更改提交,如下所示:

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

//這里是一些簡單的更新示例代碼

//首先聲明這個

private DatabaseAppHelper dbhelper;
private SQLiteDatabase db;

//初始化如下

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

//更新代碼

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

//把你的id而不是“問號”是我共享偏好中的一個功能。

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

如果您的 sqlite 行具有唯一的 id 或其他等效項,則可以使用 where 子句,如下所示

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

試試這個方法

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

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

我會用一個完整的例子來演示

以這種方式創建數據庫

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

然后創建一個類,方便CRUD -> Create|Read|Update|Delete

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

現在魔法來了

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

您必須創建必須返回 CursorAdapter 的 ProductsAdapter

所以在活動中只需調用這樣的函數

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

在此處輸入圖片說明

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

這里我已經完成了這種更新數據庫行的代碼,這是Database handler類的代碼

public Boolean updateData(String id,String name,String age,String gender){
    SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(ID,id);
    contentValues.put(NAME,name);
    contentValues.put(AGE,age);
    contentValues.put(GENDER,gender);

    sqLiteDatabase.update(TABLE_NAME,contentValues,ID+"= ?",new String[]{id});
    return true;           //Boolean value return korbe
}

我一直在嘗試更新特定行已有一段時間了,看來有兩種方法可以做到這一點。 根據我的閱讀和嘗試,您可以使用:

execSQL(String sql)方法

或者:

update(String table, ContentValues values, String whereClause, String[] whereArgs)方法。

(讓我知道這是否不正確,因為我是android新手,還是SQL新手。)

因此,讓我了解我的實際代碼。

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

我正在努力做到這一點:

更新主鍵(_id)等於1的Field1,Field2和Field3。

Eclipse在“更新”一詞的正下方給了我一條紅線,並給出了以下解釋:

SQLiteDatabase類型的方法update(String,ContentValues,String,String [])不適用於參數(String,String,String,null)

我猜我沒有正確分配ContentValues。 誰能指出我正確的方向?

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

只需提供要在 ContentValues 中更新的 rowId 和數據類型。

public void updateStatus(String id, int status){

SQLiteDatabase db = this.getWritableDatabase();

ContentValues 數據 = 新的 ContentValues();

data.put("狀態", 狀態);

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

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM