在更新查询中添加多个列

时间:2013-12-13 18:17:07

标签: java sql sqlite sql-update

我试图通过动态查询连续更新多个列。

columnnames是一个Arraylist,包含所选表的列的所有名称

Arrays.toString(row)包含应该更新行的用户输入。

我在尝试运行时在列名中收到此错误消息:没有这样的列[SNO,SNAME,STATUS,CITY]。我不知道有什么方法可以解决这个问题吗?

 query = "UPDATE " + tablename + " SET '" + columnnames  + "' = '" + Arrays.toString(row) + "' WHERE " + FirstColumn + " = '" + rowstandard + "'";

3 个答案:

答案 0 :(得分:1)

您需要单独更新每个列。你不能将它们作为数组传递。

 query = "UPDATE " + tablename + " SET "
 foreach(int i=0; i< columnnames.length; i++)
 {
     query+= "'" + columnnames[i]  + "' = '" + row[i] + "',"
 }
 query = StripLastComma(query) //Not sure how to do this in Java.
 query +="' WHERE " + FirstColumn + " = '" + rowstandard + "'"

答案 1 :(得分:0)

这不会起作用,因为set的语法是SET ColumnA =:ValueA,ColumnB =:ValueB WHERE“+ FirstColumn +”='“+ rowstandard +”'“;

答案 2 :(得分:0)

正如所指出的,更新查询的正确语法是:

UPDATE [LOW_PRIORITY] [IGNORE] table_reference
SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]

请参阅Update syntax

话虽如此,我会做这样的事情(使用guava):

StringBuilder query = new StringBuilder();
query.append("UPDATE " + tablename + " SET ");
// build a map of col name/value
Map<String, String> map = Maps.toMap(columnnames, new Function<String, String>(){
        @Override
        public String apply(String input){
            return row[columnnames.indexOf(input)].toString();
        }
    });
query.append(Joiner.on(",").withKeyValueSeparator("=").join(map));
query.append(" WHERE " + FirstColumn + " = '" + rowstandard + "'");
query.toString();