Jdbc Basic Example to connect to the 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.

Here is an example for connection to the database in java

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
  int rowcnt = 0;

  Connection con;
   con = DriverManager.getConnection("jdbc:odbc:orc","scott","tiger");
  // 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("No Of Rows Fetched " + rowcnt);


loads the JdbcOdbcDriver class into the JVM and is available to ready to use.

DriverManager.getConnection(“jdbc:odbc:orc”,“scott”,“tiger”); :-

the connection string has to be provided, which contains the 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 that 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 result set examle

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