What You Have Done So Far

This section reviews what has been covered thus far:

  • Import java.sql.* to avoid having to write long member names.

  • Build a JDBC URL.

  • Load one or more specific JDBC drivers with class.forName().

  • If necessary, adjust the connection properties.

  • Open a connection with getConnection().

  • Create a statement object.

  • Build a SQL statement.

  • Execute the SQL statement.

  • Close the statement.

  • Terminate the connection with close().

Listing 6-13 contains an example that summarizes all these steps. This example opens a connection to the database, sends a SQL query to a database with a time-out value of 180 seconds and then closes the statement and connection.

Listing 6-13: Executing a Statement

start example
// executing a statement import java.sql.*; class SimpleExample {          public static void main(String args[]) {                  String url = "jdbc:odbc:mysource";                  try {                           Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");                           Connection myConnection =                                   DriverManager.getConnection(url,                                   "javauser", "hotjava");                           Statement myStatement = myConnection.createStatement();                           myStatement.setQueryTimeout(180);                           ResultSet rs = myStatement.executeQuery("SELECT * FROM                           employees");                           myStatement.close();                           myConnection.close();                  } catch(java.lang.Exception ex) {                           ex.printStackTrace();                  }          } }
end example



JDBC 3. 0. JAVA Database Connectivity
JDBC 3: Java Database Connectivity
ISBN: 0764548751
EAN: 2147483647
Year: 2002
Pages: 148

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net