JDBC Execute Query

In this Tutorial we want to explain you an example from JDBC Execute query,

JDBC Execute Query

JDBC Execute Query


The  Execute Query in JDBC retrieve the elements from a database. In this Tutorial we want to describe you a code that helps you to understand JDBC Execute Query, For this we have a class JdbcExecutequery,Inside the main method, the list of steps that have to be done in order to access the elements from database are given below -Java.sql.* - This Java.sql* package is imported that contain the definition for set of all classes and this classes provides you the network connectivity between the database and url. 

  Loading a Driver : The next step is to load  a driver by calling a Class.forname( ) and accept the argument as driver class.When a driver is loaded, you connect the front end of your Java application to the backend database. 

 con.setAutoCommit(false) :  This method is used to disable the commit method.

 DriverManager.getConnection (  ) : The Driver Manager call get Connection ( ) method return a connection object. This method is used to connect database and a Url.  con.createConnection( ) : This method provides you an  Sql object. Once a connection is built ,your application can interact with backend database. A connection object is used to send and execute SQL Statement to a backend database.

 executeQuery (sql ) -  This method is used to retrieve the element from a database by accepting sql as argument.

 rs.next ( ) -  This method is used to retrieve the successively elements in series.

The println print the value of the number, name and date of birth.In case there is an exception occurred  in loading a database driver  in the try block. The catch block check the exception and println print the exception.


import java.sql.*;

public class JdbcExecutequery {

  public static void main(String args[]) {

  Connection con = null;
  Statement st = null;
  ResultSet rs = null;

  String url = "jdbc:mysql://localhost:3306/";
  String db = "komal";
  String driver = "com.mysql.jdbc.Driver";
  String user = "root";
  String pass = "root";

  try {
  con = DriverManager.getConnection(url + db, user, pass);
  st = con.createStatement();

  String sql = "select * from person";
  rs = st.executeQuery(sql);

  System.out.println("no.  \tName  \tDob");
  while (rs.next()) {
  System.out.print(rs.getString("id") + " \t");
  System.out.print(rs.getString("cname") + " \t");
  catch (Exception e) {


no.  	Name      	Dob
1   	Girish     	1984-06-02
2   	komal     	1984-10-27

Download code