我有一个SQLite数据库表,想连接两列,并用连接的字符串更新同一个数据库中的第三列,在它们之间留一个空格。我有通用的语法,但我似乎无法正常工作。这是我的两个陈述,有人可以指出正确语法的方向吗?非常感谢
database.update (ResturantEntry.TABLE_NAME, SET ResturantEntry.COLUMN_NAME_LOCATION = CONCAT(ResturantEntry.COLUMN_NAME, ' ', ResturantEntry.COLUMN_LOCATION));
第二条语句
database.update (ResturantEntry.TABLE_NAME, SET ResturantEntry.COLUMN_NAME_LOCATION = ResturantEntry.COLUMN_NAME + ' ' + ResturantEntry.COLUMN_LOCATION);
答案 0 :(得分:1)
除非使用SQLiteDatabase update 方法提取数据并进行串联(由于该方法如何防止SQL注入(将值用单引号引起来)),否则您不能使用SQLiteDatabase update 方法。但是,您可以通过使用类似以下内容的方法完全通过SQL进行此操作:-
String updtsql = "UPDATE " + TABLE_NAME + " SET " + COLUMN_NAME_LOCATION + " = " + COLUMN_NAME + "||" + COLUMN_LOCATION + ";";
database.execSQL(updtsql);
||
是SQL串联运算符。 但是,为什么?(修辞)您正在引入重复数据,因为不需要,因为您可以轻松提取串联的数据。
例如
您可以使用:-
提取所有COLUMN_NAME_LOCATION列的ArrayList(即包含连接数据的列)。public ArrayList<String> getNameLocationV1() {
ArrayList<String> rv = new ArrayList<>();
String[] columns = new String[]{COLUMN_NAME_LOCATION};
Cursor csr = database.query(TABLE_NAME,columns,null,null,null,null,null);
while (csr.moveToNext()) {
rv.add(csr.getString(csr.getColumnIndex(COLUMN_NAME_LOCATION)));
}
csr.close();
return rv;
}
但是,略有不同的是,提取的数据完全相同,但没有其他列的开销(即该表只需要COLUMN_NAME和COLUMN_LOCATION):-
public ArrayList<String> getNameLocationV2() {
ArrayList<String> rv = new ArrayList<>();
String concatColumnName = COLUMN_NAME + COLUMN_LOCATION;
String[] columns = new String[]{COLUMN_NAME + "||"+COLUMN_LOCATION+" AS " + concatColumnName};
Cursor csr = database.query(TABLE_NAME,columns,null,null,null,null,null);
while (csr.moveToNext()) {
rv.add(csr.getString(csr.getColumnIndex(concatColumnName)));
}
csr.close();
return rv;
}
String concatColumnName = COLUMN_NAME + COLUMN_LOCATION;
(为此可以使用COLUMN_NAME_LOCATION)