Android Studio中连接两列并更新为另一列的正确语法是什么

时间:2018-09-12 22:33:32

标签: android sqlite syntax concatenation multiple-columns

我有一个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);

1 个答案:

答案 0 :(得分:1)

除非使用SQLiteDatabase update 方法提取数据并进行串联(由于该方法如何防止SQL注入(将值用单引号引起来)),否则您不能使用SQLiteDatabase update 方法。但是,您可以通过使用类似以下内容的方法完全通过SQL进行此操作:-

    String updtsql = "UPDATE " + TABLE_NAME + " SET " + COLUMN_NAME_LOCATION + " = " + COLUMN_NAME + "||" + COLUMN_LOCATION + ";";
    database.execSQL(updtsql);
  • 注意,因为没有WHERE子句,所以它将更新每行(根据您的代码)。
  • || 是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)
  • 另一个区别是不用提供列名,而是使用将两个列(COLUMN_NAME和COLUMN_LOCATION)连接起来的表达式。
  • 这种方法更有效,因为它减少了开销;
    • 复制数据所需的额外磁盘空间,和
    • 具有额外的(不必要的)过程来更新数据