【问题标题】:Set parameters dynamically to prepared Statement in JDBC动态设置参数到 JDBC 中的预处理语句
【发布时间】:2012-07-31 09:40:33
【问题描述】:

我有一个用于所有 DAO 的通用类,我们将在其中读取查询并执行它们,如下所示。我会将参数从 DAO 发送到这个类。

Connection connection = Queries.getConnection();
String query = Queries.getQuery(queryName);//Queries i will get from xml
PreparedStatement preparedStatement =  connection.prepareStatement(query);

在 JDBC 中为准备好的语句动态设置参数的最佳方法是什么。我相信,我们在 JDBC 中没有像在 Spring JDBC 中那样命名参数的概念。在我们的项目中,我们只是简单的 JDBC。

【问题讨论】:

标签: java jdbc


【解决方案1】:

这样写:

public static int mapParams(PreparedStatement ps, Object... args) throws SQLException {
    int i = 1;
    for (Object arg : args) {         
         if (arg instanceof Date) {
        ps.setTimestamp(i++, new Timestamp(((Date) arg).getTime()));
    } else if (arg instanceof Integer) {
        ps.setInt(i++, (Integer) arg);
    } else if (arg instanceof Long) {
        ps.setLong(i++, (Long) arg);
    } else if (arg instanceof Double) {
        ps.setDouble(i++, (Double) arg);
    } else if (arg instanceof Float) {
        ps.setFloat(i++, (Float) arg);
    } else {
        ps.setString(i++, (String) arg);
    }
   }
  }
}

在查询中只需使用“?”需要在哪里设置参数。

我知道这是老派代码,但只是举个简单的例子......

【讨论】:

  • ps.setObject() 怎么样?
【解决方案2】:

好的方法是使用地图

Map<String, Object> params = new HashMap<>();
params.put("id",0);
params.put("name","test");
//more params here...


String sql = "SELECT * FROM test";

boolean first = true;

for (String paramName : params.keySet()) {
    Object paramValue = params.get(paramName);
    if (paramValue != null) {
        if (first){
            sql += " where " + paramName + "=?";
            first = false;
        } else {
            sql += " and " + paramName + "=?";
        }
    }
}

Connection connection = DataSource.getInstance().getConnection();

ps = connection.prepareStatement(sql);

int paramNumber = 1;
for (String paramName : params.keySet()) {
    Object paramValue = params.get(paramName);
    if (paramValue != null) {
        if (param instanceof Date) {
            ps.setDate(paramNumber, (Date) param);
        } else if (param instanceof Integer) {
            ps.setInt(paramNumber, (Integer) param);
        //more types here...
        } else {
            ps.setString(paramNumber, param.toString());
        }
        paramNumber ++;
    }
}

【讨论】:

    【解决方案3】:

    看看这个页面example。 您的查询应包含 ?在你想设置值的地方。

    String query = "update COFFEES set SALES = ? where COF_NAME = ?";
    

    您可以轻松设置这样的值

    preparedStatement.setInt(1, 100);
    preparedStatement.setString(2, "French_Roast");
    

    【讨论】:

      【解决方案4】:

      也许这对你来说很有趣 Named Parameters for PreparedStatement

      【讨论】:

        猜你喜欢
        • 2010-09-23
        • 1970-01-01
        • 1970-01-01
        • 2010-11-15
        • 1970-01-01
        • 2012-07-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多