Inserting a row using PreparedStatement


 

Inserting a row using PreparedStatement

In this section ,we will insert data in table of database using "PreparedStatement".

In this section ,we will insert data in table of database using "PreparedStatement".

INSERING A ROW USING PREPAREDSTATEMENT

If you want to execute a statement many time , "PreparedStatement " reduces execution time. Unlike a "Statement" object ,it is given an 'Sql' statement when it is created.This SQL statement is sent to the DBMS right away, where it is compiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement SQL statement without having to compile it first.

The advantage of using "PreparedStatement " is that you can use the same statement and supply it with different values each time you execute it.

Insertprepared.java


import java.sql.*;

public class Insertprepared{

    public static void main(String args[]) {

        Connection con = null;
        PreparedStatement pst = null;
        ResultSet rs = null;

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

        try {
            Class.forName(driver);
            con = DriverManager.getConnection(url + db, user, pass);
            con.setAutoCommit(false);// Disables auto-commit.

            String sql = "insert into student values(?,?,?) ";
            pst = con.prepareStatement(sql);

            pst.setInt(1,1642);
            pst.setString(2"Rahul");
            pst.setString(3,"1985-06-06");
            

            pst.executeUpdate();

            sql = "select * from student";
            rs = pst.executeQuery(sql);

            System.out.println("Roll No  \tName   \t\tDate of Birth");
            while (rs.next()) {
                System.out.print(rs.getInt(1"     \t");
                System.out.print(rs.getString(2"     \t");
                System.out.print(rs.getDate(3"     \t");
                System.out.println("");
            }
            rs.close();
            pst.close();
            con.close();

        catch (Exception e) {
            System.out.println(e);
        }
    }
}

OUTPUT

C:\Program Files\Java\jdk1.6.0_18\bin>java Insertprepared
Roll No                  Name             Date of Birth
2147483647          Ankit              1985-06-06
2147483648          Somesh          1984-05-05
2147483649          Rajiv              1985-06-06
2147483649          Rahul             1985-06-06

DOWNLOAD THIS CODE

Ads