Edit

Share via


Using a SQL statement with parameters

Download JDBC driver

To work with data in a SQL Server database by using a SQL statement that contains IN parameters, you can use the executeQuery method of the SQLServerPreparedStatement class. This class returns a SQLServerResultSet that contains the requested data. First create a SQLServerPreparedStatement object by using the prepareStatement method of the SQLServerConnection class.

When you construct your SQL statement, the IN parameters are specified by using the ? (question mark) character, which acts as a placeholder for the parameter values that are passed into the SQL statement. To specify a value for a parameter, use one of the setter methods of the SQLServerPreparedStatement class. The data type of the value that you pass into the SQL statement determines the setter method that you use.

When you pass a value to the setter method, you must specify not only the actual value to be used in the SQL statement, but also the parameter's ordinal placement in the SQL statement. For example, if your SQL statement contains a single parameter, its ordinal value is 1. If the statement contains two parameters, the first ordinal value is 1, while the second ordinal value is 2.

In the following example, an open connection to the AdventureWorks2025 sample database is passed in to the function. Then a SQL prepared statement is constructed and run with a single String parameter value. Then the results are read from the result set.

public static void executeStatement(Connection con) {
    try(PreparedStatement pstmt = con.prepareStatement("SELECT LastName, FirstName FROM Person.Contact WHERE LastName = ?");) {
        pstmt.setString(1, "Smith");
        ResultSet rs = pstmt.executeQuery();

        while (rs.next()) {
            System.out.println(rs.getString("LastName") + ", " + rs.getString("FirstName"));
        }
    }
    // Handle any errors that may have occurred.
    catch (SQLException e) {
        e.printStackTrace();
    }
}

See also

Using statements with SQL Prepared statement parameter performance