我一直试图更新特定行一段时间,似乎有两种方法可以做到这一点。根据我的阅读和尝试,你可以使用:
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不适用于参数(String,String, String,null)
我猜我没有正确分配ContentValues。有人能指出我正确的方向吗?
答案 0 :(得分:271)
首先制作一个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);
答案 1 :(得分:47)
简单方法:
String strSQL = "UPDATE myTable SET Column1 = someValue WHERE columnId = "+ someValue;
myDataBase.execSQL(strSQL);
答案 2 :(得分:34)
首先创建一个 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});
这是更新特定行的清除解决方案。
答案 3 :(得分:23)
此代码应修复您的示例:
ContentValues data=new ContentValues();
data.put("Field1","bob");
data.put("Field2",19);
data.put("Field3","male");
DB.update(Tablename, data, "_id=" + id, null);
答案 4 :(得分:10)
你可以试试这个......
db.execSQL("UPDATE DB_TABLE SET YOUR_COLUMN='newValue' WHERE id=6 ");
答案 5 :(得分:5)
在您的数据库中使用此代码 `
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();
答案 6 :(得分:5)
希望这会对你有所帮助:
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 :(得分:4)
您在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 :(得分:3)
可以尝试这样:
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);
答案 9 :(得分:2)
对于更新,需要调用setTransactionSuccessfull以获取更改以进行提交,如下所示:
db.beginTransaction();
try {
db.update(...)
db.setTransactionSuccessfull(); // changes get rolled back if this not called
} finally {
db.endTransaction(); // commit or rollback
}
答案 10 :(得分:2)
//这是一些简单的更新示例代码
//首先声明这个
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而不是'问号'是我共享偏好中的一个功能。
答案 11 :(得分:2)
如果您的sqlite行具有唯一ID或其他等效项,则可以使用where子句,如下所示
update .... where id = {here is your unique row id}
答案 12 :(得分: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();
}
答案 13 :(得分:1)
试试这种方式
String strFilter = "_id=" + Id;
ContentValues args = new ContentValues();
args.put(KEY_TITLE, title);
myDB.update("titles", args, strFilter, null);**
答案 14 :(得分:1)
我将通过一个完整的例子进行演示
以这种方式创建数据库
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)
}
答案 15 :(得分: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
答案 16 :(得分: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);
}
答案 17 :(得分:0)
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);
}
答案 18 :(得分:0)
只需在ContentValues中提供rowId和要更新的数据类型即可。
public void updateStatus(String id,int status){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues数据=新的ContentValues();
data.put(“状态”,状态);
db.update(TableName,data,“ columnName” +“ =” + id,null);
}
答案 19 :(得分:0)
这里我已经完成了这种更新数据库行的代码,这是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
}