【问题标题】:JDBC update statement non-nullJDBC 更新语句非空
【发布时间】:2019-05-20 22:56:07
【问题描述】:

这是我面临的一个问题:- 我正在尝试运行具有多个值的更新语句(preparedStatement),但前提是它们不为空。

例子:

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();

但有时 x 可以为空,在这种情况下我不想用空值更新 col1 列。

一种方法可能是:-

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 = ?";

有没有一种方法可以让我使用 JDBC 更干净地完成这项工作(只需一条 SQL 语句)?

谢谢,

【问题讨论】:

    标签: java jdbc


    【解决方案1】:

    构建你的 SET 子句:

    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);
    
    • 那么你当然会有条件地打电话给setString(..)
    • Joiner 来自 Guava。您可以从Commons Lang 使用StringUtils.join(..)

    【讨论】:

      猜你喜欢
      • 2020-11-12
      • 1970-01-01
      • 2015-07-23
      • 2014-12-03
      • 2012-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多