8

I have a common class for all DAO's where we will read queries and execute them as below. I will send parameters from DAO to this class.

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

what is the best way to set parameters dynamically to prepared Statement in JDBC. I believe, we don't have named parameters concept in JDBC as we have in spring JDBC. We are only simple JDBC in our project.

4

4 回答 4

9

写这样的东西:

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

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

我知道这是老派代码,但只是举一些简约的例子......

于 2012-08-02T12:15:11.680 回答
6

好方法是使用地图

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 ++;
    }
}
于 2016-04-26T19:16:19.297 回答
4

看看这个页面示例。您的查询应包含 ? 在您要设置值的位置。

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

您可以轻松设置这样的值

preparedStatement.setInt(1, 100);
preparedStatement.setString(2, "French_Roast");
于 2012-08-02T12:18:20.083 回答
1

也许这对您 来说很有趣 PreparedStatement 的命名参数

于 2012-08-02T12:23:49.957 回答