Java Reference
In-Depth Information
Now let's bring everything together into a program that simply accesses our
Finances database and displays the full contents of the Accounts table. In order to
make use of JDBC (without cumbersome package references), of course, our
program should import java.sql . In what follows, the lines corresponding to the
above six steps have been commented to indicate the relevant step numbers.
Example
import java.sql.*;
public class JDBCSelect
{
public static void main(String[] args)
{
Connection connection = null;
Statement statement = null;
ResultSet results = null;
try
{
//Step 1…
connection = DriverManager.getConnection(
"jdbc:odbc:Finances","","");
}
//For any of a number of reasons, it may not be
//possible to establish a connection…
catch(SQLException sqlEx)
{
System.out.println(
"* Cannot connect to database! *");
System.exit(1);
}
try
{
//Step 2…
statement = connection.createStatement();
String select = "SELECT * FROM Accounts";
//Step 3…
results = statement.executeQuery(select);
}
catch(SQLException sqlEx)
{
System.out.println(
"* Cannot execute query! *");
sqlEx.printStackTrace();
System.exit(1);
}
Search WWH ::




Custom Search