Search Records using Jdbc

In this blog we will know how to find the related records from the table when we enter one field value in 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 data source (for Oracle- Oracle in XE)-select it and click finish-give any name in data source name textbox-then click ok button.

 

Note: - Here Username=system, Password=pintu and Dsn name= dsn1

 

Table Creation with values

 

create table emp(empno int,empname varchar(50),sal int,job varchar(50))

insert into emp values(1,'Raj',10000,'Manager')

insert into emp values(2,'Ravi',20000,'Director')

insert into emp values(3,'Rahul',30000,'Producer')

 

SearchRecords.java

 

import java.sql.*;

import java.util.*;

public class SearchRecords

{

public static void main(String args[]) throws Exception

{

int eno,esal;

String ename,job;

char ch='c';

Scanner sc=new Scanner(System.in);

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection con=DriverManager.getConnection("jdbc:odbc:dsn1","system","pintu");

ResultSet rs;

Statement stmt=con.createStatement();

do

{

System.out.print("\nEnter the Employee Number : ");

eno=sc.nextInt();

rs=stmt.executeQuery("select * from emp where empno like "+eno);

rs.next();

ename=rs.getString("empname");

job=rs.getString("job");

System.out.println("\nNAME: "+ename+" ENO: "+eno+" Job: "+job);

System.out.println("\nPress any key to quit or c to continue :");

ch=(char)System.in.read();

}

while(ch=='c' || ch=='C');

con.close();

}

}

 

Compile

Javac SearchRecords.java

Java SearchRecords

 

 

 

Ebook Download
View all
Learn
View all