C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » Java programming language

How to display all records using JDBC in Java?

In this article, we are going to learn how to display all records of MYSQL table using JDBC through java program?
Submitted by Manu Jemini, on October 13, 2017

Prerequisite:

  1. How to create a table using JDBC in Java?
  2. How to insert records through JDBC in Java?

Note: To displaying data from MYSQL table, there should be at least one row of data must be available.

Now, we are going to establish a connection between MYSQL and JAVA using Connection class, for this we are creating an object named cn of this class.

Then, we will prepare a MySQL query statement to display records from table named employee, to execute this query statement, we will create an object of Statement class.

Then we create an object named smt of Statement class, that will be used to execute query by using executeQuery() method.

Database details:

  • Hostname: localhost
  • Port number: 3306
  • Username: root
  • Password: 123
  • Database name: demo
  • Table name: employees

Java program to display all records from a table using JDBC

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class DisplayAll {
	public static void main(String[] args) {
		try{
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			
			//serverhost = localhost, port=3306, username=root, password=123
			Connection cn=DriverManager.getConnection("jdbc:mysql://localhost:3306/demo","root","123");
			Statement smt=cn.createStatement();
			
			//query to display all records from table employee
			String q="Select * from employees";
			
			//to execute query
			ResultSet rs=smt.executeQuery(q);
			
			//to print the resultset on console
			if(rs.next()){ 
				do{
				System.out.println(rs.getString(1)+","+rs.getString(2)+","+rs.getString(3)+","+rs.getString(4)+","+rs.getString(5));
				}while(rs.next());
			}
			else{
				System.out.println("Record Not Found...");
			}
			cn.close();
		}
		catch(Exception e){
			System.out.println(e);
		}
	}
}

Output (In console)

100, Aman, 10/10/1990, Delhi, 35000








COMMENTS