0
我有表(ID,文字),我需要換列兩個值是這樣的:如何交換SQLite列中的值?
Before.
1 one.
2 two.
3 three.
After (1 and 3 swap)
1 three
2 two
3 one
我有表(ID,文字),我需要換列兩個值是這樣的:如何交換SQLite列中的值?
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;
如何從數據庫檢索id如果我有兩個值文本? – doomed
您的解決方案工作!感謝幫助! – doomed
很高興聽到它的作品。我還更新了示例以顯示如何執行查詢。 –