Search Records using Jdbc

Introduction 

 
In this blog, we will know how to find the related records from the table when we enter one field value in the console.
 
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 with valuesb
  1. create table emp(empno int,empname varchar(50),sal int,job varchar(50))  
  2. insert into emp values(1,'Raj',10000,'Manager')  
  3. insert into emp values(2,'Ravi',20000,'Director')=  
  4. insert into emp values(3,'Rahul',30000,'Producer')  
SearchRecords.java
  1. import java.sql.*;  
  2. import java.util.*;  
  3. public class SearchRecords {  
  4.  public static void main(String args[]) throws Exception {  
  5.   int eno, esal;  
  6.   String ename, job;  
  7.   char ch = 'c';  
  8.   Scanner sc = new Scanner(System.in);  
  9.   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");  
  10.   Connection con = DriverManager.getConnection("jdbc:odbc:dsn1""system""pintu");  
  11.   ResultSet rs;  
  12.   Statement stmt = con.createStatement();  
  13.   do {  
  14.    System.out.print("\nEnter the Employee Number : ");  
  15.    eno = sc.nextInt();  
  16.    rs = stmt.executeQuery("select * from emp where empno like " + eno);  
  17.    rs.next();  
  18.    ename = rs.getString("empname");  
  19.    job = rs.getString("job");  
  20.    System.out.println("\nNAME: " + ename + " ENO: " + eno + " Job: " + job);  
  21.    System.out.println("\nPress any key to quit or c to continue :");  
  22.    ch = (char) System.in.read();  
  23.   }  
  24.   while (ch == 'c' || ch == 'C');  
  25.   con.close();  
  26.  }  
  27. }   
Compile
 
Javac SearchRecords.java
 
Java SearchRecords
Next Recommended Reading Display records from database using JDBC