Artikel Terbaru

Sunday, 4 December 2011

Jdbc Basic Example to connect to database in java

Following steps for writing a sample java program to connect to database and get the result. JDBC API is provided by sun framework which contains different interfaces and classes to connect to databases.
The below diagram depicts the steps to connect to any database.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class ConnDemo {
 public static void main(String args[]) throws Exception {
  // establish connection to database this includes loading driver
  // and fetching data.
  // first step is to register jbbc driver with driver manager
  // class.forName loads class which in this case is jdbc
  // implementation of interface Driver
  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
  int rowcnt = 0;

  Connection con;
   con = DriverManager.getConnection("jdbc:odbc:orc","scott","tiger");
  System.out.println(con);
  // Once connected, we can execute any sql statement
  Statement stmt = con.createStatement();
  ResultSet rs = stmt.executeQuery("select * from employee");
  while (rs.next()) {
   System.out.println(rs.getLong("employeeid"));
   System.out.println(rs.getString("EmployeeName"));
   rowcnt++;
  }
  System.out.println("No Of Rows Fetched " + rowcnt);
 }
}
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");:- loads the JdbcOdbcDriver class into the jvm and avialble to ready to use.
DriverManager.getConnection("jdbc:odbc:orc","scott","tiger"); :-connection string has to be provided, which contains username,password,database name of oracle.
con.createStatement(); :- return the statement object which is used to get the result set using executeQuery method.
ResultSet object holds all the rows of table which are in the order by result of the query.we have to traverse the result set and fetch the each column value.
Here is the high level flow of any application connect to any database


This topic has been a very basic start to explore on JDBC example. Hopefull you have enough information to get started.
If you have any questions, please feel free to leave a comment and I will get back to you.