Display records from database using JDBC

Introduction 

 
In this blog we will know how to display records from database using JDBC (Java Database Connectivity) in the console window.
Here we use Type-1 driver (JDBC-ODBC bridge)
 

Creation of dsn(database source name) for Oracle

 
Start-Control panel- Administrative Tools- Data Sources (ODBC)-go to system DSN tab-click add button-select a driver for which you want to set up a data source (for Oracle- Oracle in XE)-select it and click finish-give any name in the data source name textbox-then click ok button.
Note: - Here Username=system, Password=pintu and DSN name=dsn1
 

Table Creation

 
Create table employee (empno int,empname varchar(50),sal int)
 

Example:- To select a record from a table 

  1. /*To select record from a table by using Statement*/    
  2. import java.sql.*;    
  3. public class select    
  4. {    
  5.  public static void main(String args[]) throws Exception {    
  6.   //Step-1      
  7.   //load the class for driver      
  8.   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");    
  9.   //Step -2      
  10.   Connection con = DriverManager.getConnection("jdbc:odbc:dsn1""system""pintu");    
  11.   //Step -3      
  12.   System.out.println("Connected to database");    
  13.   Statement stmt = con.createStatement();    
  14.   //Step-4      
  15.   ResultSet rs = stmt.executeQuery("select * from employee");    
  16.   //Fetching data from ResultSet and display      
  17.   while (rs.next())    
  18.   {    
  19.    //to fetch value from a column having number type of value      
  20.    int x = rs.getInt("empno");    
  21.    //to fetch value from a column having varchar/text type of value      
  22.    String y = rs.getString("empname");    
  23.    //to fetch value from a column having number type of value      
  24.    int z = rs.getInt("sal");    
  25.    System.out.println(x + "   " + y + " " + z);    
  26.   }    
  27.   //Step-5      
  28.   con.close();    
  29.  }    
  30. }     

Compile

 
Javac select.java
Java select
Next Recommended Reading Insert records from database using JDBC