Practical Web Programming

Tuesday, October 23, 2007

How To Connect To A Database In Java

This source codes, written in Java, demonstrates how to connect to a database using JDBC and ODBC. The source codes is well commented for you to follow easily.

import java.sql.*;

public class jdbcConnect {
//CLASS CONSTRUCTOR
public jdbcConnect() {
}

//THIS PROC WILL SET THE CONNECTION TO THE DATABASE,
//QUERY AND PRINT THE RESULT TO THE STANDARD OUTPUT
private void loadData()
{
Connection con = null;
Statement stmt = null;
ResultSet rst = null;

//SET ERROR TRAP FOR CONNECTION TO THE DATABASE
try
{
//FOR ODBC CONNECTION
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
//dsn_employee = data source name(dsn)
//un = username
//pw = password
con = DriverManager.getConnection("jdbc:odbc:dsn_employee;
UID=un;PWD=pw");

//CHECK IF THE CONNECTION TO THE DATABASE IS SUCCESSFUL
if(!con.isClosed())
{
//MAKE THE ACTUAL CONNECTION TO THE DATABASE
stmt = con.createStatement(rst.TYPE_SCROLL_SENSITIVE,
rst.CONCUR_READ_ONLY);
//EXECUTE THE SQL QUERY
rst = stmt.executeQuery("SELECT fullname FROM employee");

//CHECK IF CURRENT ROW IS THE LAST
while(!rst.isLast())
{
//SET THE ERROR TRAP FOR READING THE RECORDSET
try
{
//GO TO THE NEXT RECORD OF THE RECORDSET
rst.next();
//PRINT THE RECORD TO THE STANDARD OUTPUT
System.out.println(rst.getInt("fullname"));
}
//HANDLE TRAPPED ERROR ON READING THE RECORDSET
catch(Exception e)
{
//PRINT THE ERROR MESSAGE
System.out.println("ERROR: " + e.getMessage());
}
}
}
}
//HANDLE TRAPPED ERROR ON DATABASE CONNECTION
catch(Exception e)
{
//PRINT THE ERROR MESSAGE
System.err.println("ERROR: " + e.getMessage());
}
finally
{
try
{
if(con != null)
{
//CLOSE THE CONNECTION
con.close();
}
}
catch(SQLException e)
{
//PRINT THE ERROR MESSAGE
System.out.println("ERROR: " + e.getMessage());
}
}
}

//START OF PROGRAM
public static void main(String[] args) {
jdbcConnect dbConnect = new jdbcConnect();
dbConnect.loadData();
}
}

0 comments:

Recent Post