This section describes how to run a SELECT query statement with createStatement() and executeQuery().
After a connection object is created correctly, you need to create a statement object from the connection
object in order to execute a SQL statement on the SQL Server, see the following two method call examples:
Statement sta = con.createStatement();
sta.executeQuery("SELECT ...");
Here is a sample program that executes a SELECT statement to get the current date from the SQL Server:
/**
* ExecuteQuery.java
* Copyright (c) 2007 by Dr. Herong Yang. All rights reserved.
*/
import java.sql.*;
public class ExecuteQuery {
public static void main(String [] args) {
Connection con = null;
try {
// Load Microsoft JDBC Driver 1.0
Class.forName(
"com.microsoft.sqlserver.jdbc.SQLServerDriver");
// Obtaining a connection to SQL Server
con = DriverManager.getConnection(
"jdbc:sqlserver://localhost:1269;"
+ "user=sa;password=HerongYang;"
+ "database=AdventureWorksLT");
// Execute a query statement
Statement sta = con.createStatement();
sta.executeQuery("SELECT GETDATE()");
sta.close();
con.close();
} catch (java.lang.ClassNotFoundException e) {
System.err.println("ClassNotFoundException: "
+e.getMessage());
} catch (SQLException e) {
System.err.println("SQLException: "
+e.getMessage());
}
}
}
The program runs correctly. But you will get no output,
since the returning data from the query execution was not retrieved
and printed to the screen. See the next tutorial to know how to do this.