开发者

JDBC update statement non-null

Here is a problem I am facing:- I am trying to run an update statement (preparedStatement) with multiple values but only if开发者_如何学编程 they are not null.

Example:

String x, y,z; //initialized to some value

final String EXAMPLE_SQL = "Update Table1 set col1 = ?, col2 = ? where col3 = ?";

sqlStmt = conn.prepareStatement(EXAMPLE_SQL);
sqlStmt.SetString(1, x);
sqlStmt.SetString(2, y);
sqlStmt.SetString(3, z);
sqlStmt.executeUpdate();

but sometimes x can be null in which case I don't want to update col1 column with null value.

One way could be:-

if(x == null)
  final String EXAMPLE_SQL = "Update Table1 set col2 = ? where col3 = ?";
else
 final String EXAMPLE_SQL = "Update Table1 set col1 = ?, col2 = ? where col3 = ?";

Is there a way I can do this more cleanly (with just one SQL statement) using JDBC?

Thanks,


Build your SET clause:

StringBuilder query = new StringBuilder("Update Table 1 ");
List<String> columnsToSet = new ArrayList<String>();
if (x != null) {
    columnsToSet.add("col1 = ?");
}
if (y != null) {
    columnsToSet.add("col2 = ?");
}

String setClause = Joiner.on(", ").join(columnsToSet);
query.append(setClause);
  • then of course you will conditionally call setString(..)
  • Joiner is from Guava. You can use StringUtils.join(..) from Commons Lang.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜