28/01/25 ----------- Q)What is PreparedStatement? =>java.sql.PreparedStatement is the child of java.sql.Statement. =>Object oriented representation of already prepared (pre-compiled ) SQL statement is nothing but PreparedStatement. Q)What is the purpose of PreparedStatement? =>It is used to submit SQL statements to the DBMS. =>Whenever same SQL statement is required to be submitted to the DBMS repeatedly without compromising the performance, we use PreparedStatement. Q)How to make use of PreparedStatement in a Java application? DIAGRAM creating the PreparedStatement ------------------------------------ =>By calling prepareStatement() method on the Connection object, java.sql.PreparedStatement object is created. For eg. PreparedStatement ps1=connection.mprepareStateent("INSERT INTO ACCOUNT VALUES(?,?,?)"); PreparedStatement ps2=connection.prepareStatement("UPDATE ACCOUNT SET BALANCE=BALANCE+? WHERE ACCNO=?"); PreparedStatement ps3=connection.prepareStatement("SELECT BALANCE FROM ACCOUNT WHERE ACCNO=?"); PreparedStatement ps4=connection.prepareStatement("DELERE FROM ACCOUNT WHERE ACCNO=?"); Binding of Parameters ------------------------- =>Supplying the values to the place holders(question marks) is nothing but binding of parameters. =>Parameter binding is done by using setXXX methods of PreparedStatement object. These methods take 2 arguments. 1)palce holder number(index) 2)value For eg. ps1.setInt(1,10001); ps1.setString(2,"Rama"); ps1.setDouble(3,50000); Submitting the SQL statement ---------------------------------- =>PreparedStatement object has 2 methods to submit the SQL statements to the DBMS. 1)executeUpdate() 2)executeQuery() For eg. int re=ps1.executeUpdate();//DML ResultSet rs=ps3.executeQuery();//DRL Q)Java application to store multiple accounts into the database. import java.sql.DriverManager; import java.sql.Connection; import java.sql.PreparedStatement; class AccountsStoringApplication{ public static void main(String args[]) throws Exception{ Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/ashokitdb","root","ashokit"); PreparedStatement preparedStatement=connection.prepareStatement("INSERT INTO ACCOUNT VALUES(?,?,?)"); preparedStatement.setInt(1,10003); preparedStatement.setString(2,"David"); preparedStatement.setDouble(3,60000); int re=preparedStatement.executeUpdate(); System.out.println(re+" account stored into the database"); preparedStatement.setInt(1,10004); preparedStatement.setString(2,"Singh"); preparedStatement.setDouble(3,50000); re=preparedStatement.executeUpdate(); System.out.println(re+" more account stored into the database"); preparedStatement.close(); connection.close(); } }