Blog

Display records from database using JDBC

By Satyapriya Nayak Blogs | Java Sep 24, 2011
In this blog we will know how to display records from database using JDBC (Java Database Connectivity) in console window.
Download Files: Display.rar

In this blog we will know how to display records from database using JDBC (Java Database Connectivity) in 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 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

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

 

Example:- To select record from a table

 

/*To select record from a table by using Statement*/

import java.sql.*;

public class select

{

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

 //Step-1

//load the class for driver

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

//Step -2

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

//Step -3

System.out.println("Connected to database");

Statement stmt=con.createStatement();

//Step-4

ResultSet rs=stmt.executeQuery("select * from employee");

//Fetching data from ResultSet and display

while(rs.next())

{

//to fetch value from a column having number type of value

int x=rs.getInt("empno");

//to fetch value from a column having varchar/text type of value

String y=rs.getString("empname");

//to fetch value from a column having number type of value

int z=rs.getInt("sal");

System.out.println(x+"   "+y +" "+z);

}

//Step-5

con.close();

}

}

Compile

Javac select.java

Java select

 

COMMENT USING