Sunday, December 4, 2011

Jdbc Basic Example to connect to database in java

Following steps for writing a sample java program to connect to the 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.
jdbc java example


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 a table which are in the order by the result of the query.we have to traverse the result set and fetch each column value.
Here is the high-level flow of an application connect to any database
jdbc java statement resultset examle



This topic has been a very basic start to explore on JDBC example. Hopefully, 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.


EmoticonEmoticon

Note: Only a member of this blog may post a comment.