Creating a database connection using JDBC involves 3 main steps.
1. Loading the database driver
2. Getting the connection using the driver manager
3. Using the connection to access the underlying database.
The sample code below explains the steps in detail.
import java.sql.*;
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try{
//Load the database driver class
Class.forName("your databse driver name");
//Example, mySql driver is com.mysql.jdbc.Driver
//Get the connection
conn = DriverManager.getConnection( "dburl","user","password") ;
//Create a Statement object.
stmt = conn.createStatement();
//Get a ResultSet
rs = stmt.executeQuery("your query here");
//Loop through the results
while(rs.next()){
//get to each column in a row.
//for example to get a value from a column named 'user'
String userName = rs.getString("user");
}
}catch( Throwable t){
//handle error here
}
finally{
//note the sequence of closing the objects. rs first followed
// by stmt and connection objects
try{
if(rs != null) rs.close();
}catch(Throwable t){t.printStackTrace();}
try{
if(stmt != null) stmt.close();
}catch(Throwable t){t.printStackTrace();}
try{
if(con != null) con.close();
}catch(Throwable t){t.printStackTrace();}
}
Hope this helps!
Sincerly,
Your friends at
www.javaadvice.com www.javaadvice.com - The one stop resource for all your Java questions and answers.