JDBC access database

JDBC is a Java Database Connectivity. The JDBC Connectivity provides API classes and interfaces for connecting the front end in Java application with database connections.

JDBC access database

JDBC access database

     

JDBC is a Java Database Connectivity. The JDBC Connectivity provides API classes and interfaces for connecting the front end in Java application with database connections. 

Understand with Example

In this Tutorial we want to describe you a code that helps in understanding JDBC access database. The code illustrates the list of following steps-

  1. The first and foremost step is to import a package import java.sql.*;This package import the list of all classes defined in java.sql.*.
  2. database driver Loading - The second step is to load the driver class by invoking Class.forName( ) with the Driver class name passed as an argument. Once your driver is loaded ,you can connect the front end of the Java application to the backend database. In case there is an exception occurred  in loading a database in the try block. The catch block check the exception and println print the exception.
  3. st = con.createconnection( ) -This is used to create Sql object. Once a connection is established ,you can interact with backend database. A connection object is used to send and execute SQL Statement to a backend database.
  4. rs = st.executequery(sql)   -  This is used to for select query in sql and the value retrieved from it stored in  result set rs.The Result Set enables you to access a table containing data. The table row retrieved in a sequence.
  5. next( ) -  The next method is used to retrieve successively element through the rows obtained from a result set.

Finally the println print the Id and name from the result set obtained from database. lastly all the result set, connection and statement is closed.

JdbcGetInt.java

import java.sql.*;
public class JdbcGetInt {
    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 {
            Class.forName(driver);
            con = DriverManager.getConnection(url + db, user, pass);
            st = con.createStatement();
            String sql = "select * from person";
            rs = st.executeQuery(sql);
            
            System.out.println("Id\tName");
            while (rs.next()) {
                System.out.print(rs.getInt(1));
                System.out.println("\t"+rs.getString(2));
            }
            rs.close();
            st.close();
            con.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

Output

Id	Name
4	Komal
5	Ajay
6	Santosh

Download code