Connecting to a Database - Step by Step

Class.forName("[nameOfDriver]");

//For Microsoft SQL Server that would be
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");


 

For the JVM to be able to find that class, you need to make sure the class is in your classpath.
Usually the class is located within a .jar-file that can be downloaded from the database vendor.


Creating the database connection

To create the connection you use the static method getConnection() of the java.sql.DriverManager class.
The method has several overloaded variants, and one of them takes an url, userid and password as arguments.
The database url slightly differs from one type of database to another. For Microsoft SQL Server it looks like this:


//The values within square brackets are the ones to change to suite your environment,
//and the square brackets should thus not be included
Connection con = DriverManager.getConnection("jdbc:sqlserver://[server]:[port];databaseName=[nameofdatabase]", 
         "[userid]", 
         "[password]");


Create the Statement object and executing a query

Now that we have established a connection, we want to create a Statement object and execute an sql query.


Statement statement = con.createStatement();
ResultSet rs = statement.executeQuery("SELECT * FROM table");


Now we have retrieved the data from the table called 'table' into a ResultSet and all we have to do now is loop through it.
Assume the table has two columns called id which is of type int, and value which is of type varchar:


//The next() mehtod jumps to the next row in the ResultSet.
//When the last row has been processed, the method returns false.

while (rs.next()) {

   System.out.println(rs.getInt("id") + " - " + rs.getString("value"));
   
}


Cleaning up resources

Now all we have to do is close the connection. Actually we should close all of the instances of Connection, Statement and ResultSet and 
it's done in reverse order from which they were created:


if (rs != null)
   rs.close();
if (statement != null)
   statement.close();
if (con != null)
   con.close();


For many of the code statements above it is required to handle an SQLException in case anything goes wrong.
Thus you'll have to enclose much of the code in a try / catch block which were excluded in the example to make it more readable.


// Declare the variables outside the try block to be able to call them 
// in a finally block where the closing should take place.
Connection con = null;
Statement stmt = null;
ResultSet rs = null;


try {

   //all code here

} catch (SQLException ex) {

   ex.printStackTrace();

} finally {

   //the code for closing here
}

0 comments:

                                                                

Site Meter