1

How do I create a batch update that won't update a column if the passed-in parameter value is null? For example:

String UPDATE_STMT = "UPDATE MY_TABLE SET col1 = ?, col2 = ?, col3 = ?";
Connection conn = getConnection();
PreparedStatement pstmt = conn.preparedStatement(UPDATE_STMT);

List items = getItems();
for (ItemType item : items) {

    stmt.setString(1, item.x);
    stmt.setString(2, item.y);
    stmt.setString(3, item.z);
}

pstmt.executeBatch();

How do I code it so that col1 will only be updated with the value of item.x if item.x is not null or empty? if item.x is null/empty, I don't want the current value in the col1 field to be overridden. This is for an Oracle 10g database.

4

3 回答 3

1

我想它应该适合你:

String UPDATE_STMT = "UPDATE MY_TABLE SET col1 =   
CASE WHEN ? IS NULL THEN col1 ELSE ? END, col2 = ?, col3 = ?";

注意,现在你需要设置 item.x 两次,stmt.setString(1, item.x); stmt.setString(2, item.x);

于 2012-09-17T16:36:27.390 回答
0

如果您不想要alex07 的 Oracle 特定解决方案,只需为每组项目重新生成准备好的语句。

Connection conn = getConnection();

List items = getItems();
for (ItemType item : items) {

    String UPDATE_STMT = "UPDATE MY_TABLE SET ";
    if (item.x != null) {UPDATE_STMT += "col1 = ?, ";}
    UPDATE_STMT += "col2 = ?, col3 = ?";

    PreparedStatement pstmt = conn.preparedStatement(UPDATE_STMT);

    int count = 0;
    if (item.x != null) {pstmt.setString(++count, item.x);}
    pstmt.setString(++count, item.y);
    pstmt.setString(++count, item.z);

    pstmt.executeBatch();
}
于 2012-09-17T17:02:46.607 回答
0

如果 item.x 为空,则使用 COALESCE 返回 col1:

String UPDATE_STMT = "UPDATE MY_TABLE SET col1 = COALESCE(?,col1), col2 = ?, col3 = ?"

然后您需要做的就是确保 item.x 始终为空,而不是空字符串。

于 2012-09-17T16:37:10.237 回答