JDBC Prepared Statement Example
Prepared Statement is different from Statement object, When it is created ,it is represented as SQL statement. The advantage of this statement is SQL statement sent to the DBMS,in which it is compiled. The Prepared Statement is helpful in execute and run a same Statement object many times, thus we normally uses prepared statement to reduces execution time.
Understand with Example
The code illustrates an example from JDBC Prepared Statement Example. The code include a class JDBC PreparedstatementExample,Inside the class we have a try block, that include a main ( ) method. The main method ( ) include the list of steps as follow -
Here is the video tutorial of: "How to use PreparedStatement in Java?"
Importing a package Java.sql :Network Interface for communicating between front -end application and database.
Inside the try block we load a driver by calling a class.forName( ),that accept driver class as argument.
DriverManager.getConnection ( ) :This method is used to built a connection between url and database.
prepareStatement
( ) : This method is used to execute and run a same Statement
object
many times, thus it normally uses prepared statement to reduces execution time.
set
String XXX( ) : If you want to supply values in place of the question mark
placeholders before you can execute a Prepared Statement
object. This
can be done by calling setXXX
methods defined in the Prepared Statement
class. The value you want to substitute for a question mark is a Java string
,
you can set and call the method set String as given below example.
executeQuery ( ) : This method is used to return record set, The return record set is assigned in a result set. The select statement return you a record set .
next ( ): This method return you the next element in the series.
Finally the println print the Employee Id,First Name in the output.
In case the exception exist in a try block, the catch block caught and handle the exception. JdbcPreparedstatementExample.java
import java.sql.*; public class JdbcPreparedstatementExample { static private final String driver = "sun.jdbc.odbc.JdbcOdbcDriver"; static private final String connection = "jdbc:odbc:emp"; public static void main(String args[]) { Connection con = null; PreparedStatement pst = null; ResultSet rs = null; try { Class.forName(driver); con = DriverManager.getConnection(connection); String sql = "select * from Employees where FirstName " + "in(?,?,?)"; pst = con.prepareStatement(sql); pst.setString(1, "komal"); pst.setString(2, "ajay"); pst.setString(3, "santosh"); rs = pst.executeQuery(); System.out.println("EmployeeID\tFirstName"); while (rs.next()) { System.out.print(" "+rs.getString(1)); System.out.print("\t\t"+rs.getString(2)); System.out.println("\t\t"+rs.getString(3)); } } catch (Exception e) { System.out.println(e); } } }
Output
EmployeeID FirstName LastName 1 komal singh 2 ajay rawat 5 santosh nagi |