我有表( id ,文本),我需要在这样的列中交换两个值:
Before.
1 one.
2 two.
3 three.
After ( 1 and 3 swap)
1 three
2 two
3 one
要更新每一行,你需要这样的东西:
void updateMyTableText (MyTableRow row)
{
ContentValues values = new ContentValues();
values.put ("text", MyTableRow.text);
String where = "id = ?";
String[] whereArgs = new String[1];
whereArgs[0] = Long.toString (row.id);
getDb().update ("MyTable", values, where, whereArgs);
}
MyTableRow 在哪里
class MyTableRow
{
long id;
String text;
}
您还需要一些查询来获取第 1 行和第 3 行的“文本”。
这是进行查询的一种方法:
long getId (String text)
{
// do the query
String query = "select id from MyTable where text = ? ";
String[] args = new String[1];
args[0] = text;
Cursor cursor = getDb().rawQuery (query, args);
if (cursor == null)
throw new IllegalStateException ("cursor is null");
try
{
// get the results
if (!cursor.moveToNext())
return -1; // row not found
long id = cursor.getLong (0);
return id;
}
finally
{
cursor.close();
}
}
您是否尝试更改行本身的值?大多数数据库系统不允许您随意交换值,因为假设它们是永久关联的。您可以发出 UPDATE 命令来永久修改这些值,但暂时执行此操作可能会在返回数据后处理问题。
UPDATE table_name
SET text=three
WHERE id=1;
UPDATE table_name
SET text=one
WHERE id=3;
// Assuming id1 < id2
void swap(id1,id2)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues CV = new ContentValues();
// First get the 2 rows
Cursor res = db.rawQuery("SELECT COLUMN_NAME FROM "+ TABLE_NAME +" WHERE ID IN ("+id1+","+id2+") ORDER BY ID ASC",null);
res.moveToFirst();
CV.put("COLUMN_NAME",res.getString(0));
//Update 1st row with 2nd item
db.update(TABLE_NAME,CV,"ID = ?",new String[]{id2+""});
res.moveToNext();
CV.put("COLUMN_NAME",res.getString(0));
//Update 2nd row with 1st item
db.update(TABLE_NAME,CV,"ID = ?",new String[]{id1+""});
}