You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JDBC中为带占位符的SELECT语句调用setString方法?

JDBC中为带占位符的SQL设置参数的正确方式

你当前的问题在于使用了普通的Statement对象执行带?占位符的SQL——普通Statement并不支持参数绑定操作,只有PreparedStatement才具备调用setString等方法设置占位符参数的能力,同时它还能有效避免SQL注入风险。

正确的做法是把执行查询的Statement替换为PreparedStatement,具体步骤如下:

  • 用connection.prepareStatement(SELECT_ST)创建PreparedStatement对象,传入带占位符的SQL语句
  • 调用setString(int parameterIndex, String x)方法为占位符赋值,注意参数索引从1开始
  • 调用executeQuery()(无需再传入SQL)获取结果集

修改后的完整代码如下:

public static final String SELECT_ST = "SELECT name, car FROM rating WHERE car= ?";

try (Connection connection = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWD);
     PreparedStatement statement1 = connection.prepareStatement(INSERT_ST);
     // 将普通Statement替换为PreparedStatement,同时指定结果集类型和并发模式
     PreparedStatement statement2 = connection.prepareStatement(SELECT_ST, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
) {
    // 为第一个占位符设置参数(索引从1开始)
    statement2.setString(1, "要查询的车型");
    
    try(ResultSet rs = statement2.executeQuery()){
        // 处理结果集的示例代码
        while(rs.next()){
            String name = rs.getString("name");
            String car = rs.getString("car");
            // 后续业务逻辑
        }
    }
}catch (SQLException e) {
    throw new ScoreException("Some problem here", e);
}

内容的提问来源于stack exchange,提问作者david

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 15:35:05