Using an SQL statement with no parameters

Download JDBC driver

To work with data in a SQL Server database by using an SQL statement that contains no parameters, you can use the executeQuery method of the SQLServerStatement class to return a SQLServerResultSet that will contain the requested data. First create a SQLServerStatement object by using the createStatement method of the SQLServerConnection class.

In the following example, an open connection to the AdventureWorks2022 sample database is passed in to the executeStatement function. From there, a SQL statement is constructed and run. Finally, the results are read from the result set.

public static void executeStatement(Connection con) {
    try(Statement stmt = con.createStatement();) {
        String SQL = "SELECT LastName, FirstName FROM Person.Contact ORDER BY LastName";
        ResultSet rs = stmt.executeQuery(SQL);

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

For more information about using result sets, see Managing result sets with the JDBC driver.

See also

Using statements with SQL