10.2 Connecting to the database |
try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //loads the driver } catch(ClassNotFoundException e) { System.out.println("Could not load JDBC driver !"); System.exit(1); }
Connection dbConnection = null; String url = "jdbc:odbc:fred"; String userID = "AUserID"; String password = "APassword"; try { dbConnection = DriverManager.getConnection(url, userID, password); } catch (SQLException e) { System.out.println("Database Error. Could not connect : " + e); System.exit(1); } catch (Exception e) { System.out.println("Error. Could not Connect : " + e); System.exit(1); }The URL string that is passed to the getConnection() method is used by the DriverManager class to determine which JDBC driver to use. The URL string above specifies the use of the JDBC to ODBC bridge, using the ODBC datasource "fred".
Two types of exceptions are caught above. Most of the functions in the
JDBC throw a SQLException if they have a problem, however some JDBC
drivers throw other exceptions if there is a problem with in the getConnection()
method.