Android 中的 SQLite 如何更新特定行

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

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

类型中的方法更新(String、 ContentValue、 String、 String []) SQLiteDatabase 不适用于参数(String,String, String,null)

我猜我没有正确地分配内容值。有人能给我指出正确的方向吗?

395231 次浏览

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

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

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

首先创建 ContentValue 对象:

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

在数据库中使用此代码 `

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();
  1. 我个人比较喜欢。更新它的方便。但是 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);

希望这个能帮到你:

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

试试这条路

  String strFilter = "_id=" + Id;
ContentValues args = new ContentValues();
args.put(KEY_TITLE, title);
myDB.update("titles", args, strFilter, null);**
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);
}

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

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

首先创建一个 内容价值对象:

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

然后使用更新方法。注意,第三个参数是 where 子句。“ ?”只是个替代品。它将被替换为第四个参数(id)

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

这是更新特定行的最干净的解决方案。

//下面是一些简单的更新示例代码

//首先声明

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

//在我的共享首选项中,将 ur id 替换为“问号”是一个函数。

可以这样试试:

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

你可以试试这个。

db.execSQL("UPDATE DB_TABLE SET YOUR_COLUMN='newValue' WHERE id=6 ");
 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 中的更新方法:

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

只要给出 rowId 和将要在 ContentValue 中更新的数据类型。

Public void updateStatus (String id,int status){

SQLiteDatabase db = this. getWritableDatabase () ;

内容值数据 = 新的内容值() ;

Put (“ status”,status) ;

Update (TableName,data,“ columnName”+ “ =”+ id,null) ;

}

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

这样创建数据库

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

您必须创建 ProductsAdapter,它必须返回 CursorAdapter

在一个活动中,像这样调用函数

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

enter image description here

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

这里我已经完成了这类代码的数据库更新行,这是数据库处理程序类的代码

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
}