【问题标题】:SQLite in Android How to update a specific rowAndroid中的SQLite如何更新特定行
【发布时间】:2012-04-05 14:37:00
【问题描述】:

一段时间以来,我一直在尝试更新特定行,似乎有两种方法可以做到这一点。根据我的阅读和尝试,您可以使用:

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 在“更新”这个词的正下方给了我一条红线,并给了我这样的解释:

类型中的方法update(String, ContentValues, String, String[]) SQLiteDatabase 不适用于参数(字符串、字符串、 字符串,空)

我猜我没有正确分配 ContentValues。谁能指出我正确的方向?

【问题讨论】:

    标签: java android sql eclipse sqlite


    【解决方案1】:

    首先制作一个 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});
    

    【讨论】:

    • Eclipse 在“Field1”、“Field2”和“Field3”上给了我红色下划线。有什么建议吗?
    • 对不起,我以为它们是在您的代码中声明的变量。将它们放在双引号中。
    • 感谢您成为第一个给出正确答案的人。为我节省了很多时间。非常感谢。
    • 如果我想检查该行是否存在于表中然后决定是否更新或插入一行?
    • 这实际上是一个走动。 db.update() 的第三个参数应该只是 where 子句,第四个是实际条件值。在这种情况下,该行应该是:myDB.update(TableName, cv, "_id=?", new String[]{id})。 SQLite 会自动将第四个参数填入“?”在第三个参数中,即 WHERE 子句。如果您的第三个参数包含 n "?"s ,则第四个参数应该是长度为 n 的 String[]
    【解决方案2】:

    简单的方法:

    String strSQL = "UPDATE myTable SET Column1 = someValue WHERE columnId = "+ someValue;
    
    myDataBase.execSQL(strSQL);
    

    【讨论】:

    • 此代码将抛出 IllegalArgumentException。如果您在没有 ContentValues 的情况下执行查询,最好完全避免使用第二个参数。喜欢:myDataBase.execSQL(strSQL);
    • 使用execSQL() 进行更新将不起作用。阅读execSQL() with UPDATE doesn't update
    • 这样做存在严重的安全风险,因为有人可以将 SQL 语句传递给“someValue”变量,这可能会改变整个数据库。因此,在进行任何数据库操作时,请始终尝试执行准备好的语句。
    【解决方案3】:

    首先创建一个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});
    

    这是更新特定行的最简洁的解决方案。

    【讨论】:

    • 自使用以来的最佳方式?是安全的。
    • 那是什么?做什么?
    • 参数方法用 ?是最好和最安全的方法。这应该是公认的答案。编写 sql 语句时不要使用字符串连接!
    • where子句包含两个字段时如何使用?
    【解决方案4】:
    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);
    

    【讨论】:

      【解决方案5】:

      你可以试试这个...

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

      【讨论】:

        【解决方案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;   
         }
        

        【讨论】:

          【解决方案7】:

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

          【讨论】:

            【解决方案8】:

            在您的数据库中使用此代码 `

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

            【讨论】:

              【解决方案9】:

              可以这样试试:

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

              【讨论】:

                【解决方案10】:

                如果你的 sqlite 行有一个唯一的 id 或其他等价物,你可以使用 where 子句,像这样

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

                【讨论】:

                • 仍然收到与我的问题中所述相同的错误。我确实将第三个参数(String whereClause)更改为"where _id = 1"。这种变化也反映在我的问题中。
                【解决方案11】:

                对于更新,需要调用 setTransactionSuccessfull 来提交更改,如下所示:

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

                【讨论】:

                  【解决方案12】:

                  //这里是一些简单的更新示例代码

                  //先声明这个

                  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代替“问号”是我共享偏好中的一个功能。

                  【讨论】:

                    【解决方案13】:
                     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();
                    }
                    

                    【讨论】:

                      【解决方案14】:

                      试试这个方法

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

                      【讨论】:

                        【解决方案15】:

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

                        【讨论】:

                          【解决方案16】:

                          我会用一个完整的例子来演示

                          以这种方式创建您的数据库

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

                          【讨论】:

                            【解决方案17】:
                            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
                            

                            【讨论】:

                              【解决方案18】:

                              这里我已经完成了这种更新数据库行的代码,这是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
                              }
                              

                              【讨论】:

                                【解决方案19】:
                                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);
                                }
                                

                                【讨论】:

                                  【解决方案20】:

                                  只需在 ContentValues 中提供 rowId 和要更新的数据类型即可。

                                  public void updateStatus(String id , int status){

                                  SQLiteDatabase db = this.getWritableDatabase();

                                  ContentValues 数据 = 新 ContentValues();

                                  data.put("status", status);

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

                                  }

                                  【讨论】:

                                    猜你喜欢
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 2021-05-17
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 1970-01-01
                                    相关资源
                                    最近更新 更多