Dynamic SQL with PreparedStatement JDBC

Dynamic SQL with PreparedStatement JDBC


In the following program, an Employee record is inserted using PreparedStatement(executing dynamic SQL statements). PreparedStatement along with CallableStatement is fully discussed in Difference between Statement, PreparedStatement, CallableStatement.

Example on PreparedStatement JDBC


PreparedStatement JDBC
Output screenshot on PreparedStatement JDBC

prepareStatement(String) method of Connection interface returns an object of PreparedStatement interface. It is to be remembered that createStatement(String) method Connection interface returns an object of Statement interface.

setInt(), setString() and setDouble() are the methods of PreparedStatement interface. Note, getInt(), getString() and getDouble() are the methods of ResultSet interface.

PreparedStatement execution is faster as PreparedStatement is treated as "partially compiled" statement. At runtime, only values are compiled and inserted.

PreparedStatement pst = con.prepareStatement(“insert into Employee(empid, empname, empsal) values(?,?,?)”);

The above statement can be replaced with the following. It is possible only when all the table fields are inserted.

PreparedStatement pst = con.prepareStatement(“insert into Employee values(?,?,?)”);

Practice more programs to have command over PreparedStatement used very much in realtime applications.

Leave a Reply

Your email address will not be published. Required fields are marked *