简体   繁体   中英

MSSQL SELECT Statement Error in WHERE clause

I'm running simple java code to get results from DB. But it always gives index 1 is out of range. How can I set variable in to WHERE clause

public String getTransNumberFromDB(String cli) throws Exception {
    System.out.println(clid);
    String sql = "SELECT * FROM [MediaPrima_IVR].[dbo].[call_back]  WHERE CLID= '?' and FLAG = '0'";
    System.out.println(sql);
    this.Con = DriverManager.getConnection(this.url, this.dbUName,
            this.dbPswd);
    PreparedStatement stmt = this.Con.prepareStatement(sql);
    stmt.setString(1, clid);
    ResultSet rs;

    try {
        rs = stmt.executeQuery();

        while (rs.next()) {
            getCLIFromResultSet(rs);
            System.out.println("Getting Number from call back database...");
            System.out.println("Number from call back database is:" + getNumber());
        }
    } catch (Exception e) {
        System.out.println("Exception is : " + e);
        throw e;
    } finally {
        stmt.close();
        this.Con.close();
    }
    return getNumber();
}

private String getCLIFromResultSet(ResultSet rs) throws SQLException {

    setNumber(rs.getString("CALL_ID"));
    return Number;
}

But I returned the error as follows.

com.microsoft.sqlserver.jdbc.SQLServerException: The index 1 is out of range.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:170)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.setterGetParam(SQLServerPreparedStatement.java:698)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.setValue(SQLServerPreparedStatement.java:707)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.setString(SQLServerPreparedStatement.java:1015)

Please help to sort out this issue.

? in sql should not be in ' ' (single quotes). It should be just ?.

 String sql = "SELECT * FROM [MediaPrima_IVR].[dbo].[call_back]  WHERE CLID= ? and FLAG = '0'";
String sql = "SELECT * FROM [MediaPrima_IVR].[dbo].[call_back]  WHERE CLID= ? and FLAG = '0'";
System.out.println(sql);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM