Using an SQL Statement with No Parameters

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. To do this, you must first create a SQLServerStatement object by using the createStatement method of the SQLServerConnection class.

In the following example, an open connection to the SQL Server 2005 AdventureWorks sample database is passed in to the function, an SQL statement is constructed and run, and then the results are read from the result set.

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

      while (rs.next()) {
         System.out.println(rs.getString("LastName") + ", " + rs.getString("FirstName"));
      }
      rs.close();
      stmt.close();
   }
   catch (Exception e) {
      e.printStackTrace();
   }
}

For more information about using result sets, see Managing Result Sets with the JDBC Driver.

See Also

Other Resources

Using Statements with SQL