Home           J2EE Concepts           JMS           Java Language           Contact           Back           Next           Bookmark this Page          










Some useful tips related to:
 - health & fitness
 - vehicle care
 - cooking
 - misc household tasks

Establishing a database connection using JDBC


On theoretical level there are two main steps involved here:
- Load the database driver.
- Create the connection.


Loading the driver


This involves just one line of code:
Class.forName("");

For e.g.; to use JDBC-ODBC bridge driver, use following line of code:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Here calling Class.forName would create an instance of the driver and register that with DriverManager.


Creating Connection


Typically this task also involves just one line of code:
Connection con = DriverManager.getConnection("DB url","DB login", "DB password");

Let us assume that you're using JDBC-ODBC Bridge to connect to a database. You also have a ODBC Data Source named Test, user name is myUser & password is myPassword. In this case, the connection invocation code would be:
Connection con = DriverManager.getConnection("jdbc:odbc:Test","myUser", "myPassword");


That was all as far as establishing a DB connection is concerned. However, you won't stop here; you would want to execute some SQL queries also. To do that, you would need to create a statement (it is an object for executing query). Later on you would execute a query & optionally you would store the results based on your query's output.
A sample code to do this is given below:
Connection con = DriverManager.getConnection("DB url","DB login", "DB password");

Let us assume that you're using JDBC-ODBC Bridge to connect to a database. You also have a ODBC Data Source named Test, user name is myUser & password is myPassword. In this case, the connection invocation code would be:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:Test","myUser", "myPassword");
con = DriverManager.getConnection(url, "borg", "");
Statement s = con.createStatement();
String query = "select * from myTable";
ResultSet result = select.executeQuery (query);

Don't forget to enclose the JDBC statements in exception handling block.