JDBC

JDBC is Java database connectivity . if we want to fire sql queries using java program the JDBC will  be used. there are 4 steps of JDBC as below

  1. Loading a Driver
  2. Creating Connection
  3. Creating a statement
  4. Executing a query.

Lets understand each steps one by one. (we are considering my-sql as database)

Loading a driver : – to connected the java to database there are different functions already defined in some classes and those classes a packaged into a particular jar. this is nothing but a driver. for e.g. my-sql-connector.jar is used for my sql database ojdbc.jar is used for oracle. the syntax of loading a driver is as below.

Class.forName("com.mysql.jdbc.Driver")

Creating a connection :- The connection will be created using below syntax

 String url="jdbc:mysql://localhost:3306/DatabaseName";

String user="root";

String password="root";

Connection con = DriverManager.getConnection(url,user,password);

Creating Statement :- statement will be created using below syntax

Statement st = con.createStatement();

Execute the query :- Now if the sql query is DDL Query(data definition language query – e.g. select) the we use the method executeQuery() & if the sql query is DML Quer y(data Manupulation language query – insert,update,delete) the we use the method executeUpdate. syntax is as below.

//DDL Query
String sqlSelect = "Select * from student";
st.executeQuery(sqlSelect);

//DML Query
String sqlInsert = "insert into student values(1,'amol','IT')";
st.executeUpdate(sqlInsert);

please consider below is an example code for better understanding

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


public class JdbcExample {

    public static void main(String[] args) throws ClassNotFoundException, SQLException {

        Class.forName("com.mysql.jdbc.Driver");

        String url="jdbc:mysql://localhost:3306/dbAmol";

        String user="root";

        String password="root";

        Connection con = DriverManager.getConnection(url, user, password);

        Statement st = con.createStatement();

        //DDL Query
        String sqlSelect = "Select * from student";
        Resultset rs = st.executeQuery(sqlSelect);
         while(rs.next())
          {
           rs.getInt("id");
           rs.getString("name");
           rs.getString("branch");
         } 

// DML Query 
String sqlInsert = "insert into student values(1,'amol','IT')"; 
st.executeUpdate(sqlInsert); 
 } 
}