Home » Java programming language

How to display particular record by a field using JDBC in Java?

In this article, we are going to learn how to display a particular record by a field from MYSQL table using JDBC through java program?
Submitted by Manu Jemini, on October 14, 2017

Prerequisite:

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

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

First of all, we establish a connection between MYSQL and Java using Connection class, by creating an object named cn of this class.

Then we take input of a field, of which we want to display record.

Then, we will prepare a MySQL query statement to display record from table with a where clause, 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.

After this, we will prepare an object named rs of class ResultSet, which gives us the result of query execution.

Database details:

  • Hostname: localhost
  • Port number: 3306
  • Username: root
  • Password: 123
  • Database name: demo
  • Table name: employees
  • Field: empid (employee id)

Java program to display particular record by a field using JDBC

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

public class DisplayByID {
	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();

			DataInputStream KB=new DataInputStream(System.in);

			//input a particular employee id of which we want to display record
			System.out.print("Enter Employee ID:");
			String eid=KB.readLine();

			//query to display a particular record from table employee where empid(employee id) is equals to eid
			String q="Select * from employees where empid='"+eid+"'";

			//to execute query
			ResultSet rs=smt.executeQuery(q);

			//to print the resultset on console
			if(rs.next())
			{
				System.out.println(rs.getString(1)+","+rs.getString(2)+","+rs.getString(3)+","+rs.getString(4)+","+rs.getString(5));
			}
			else
			{
				System.out.println("Record Not Found...");
			}
			cn.close();
		}
		catch(Exception e){
			System.out.println(e);
		}
	}
}

Output (In console)

Enter Employee ID :100
100, Aman, 10/10/1990, Delhi, 35000


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.