Powered by Blogger.

Java JDBC Prepared Statements

>> Thursday, March 31, 2011

Java JDBC Prepared statements are pre-compiled SQL statements. Precompiled SQL is useful if the same SQL is to be executed repeatedly, for example, in a loop. Prepared statements in java only save you time if you expect to execute the same SQL over again. Every java sql prepared statement is compiled at some point. To use a java preparedstatements, you must first create a object by calling the Connection.prepareStatement() method. JDBC PreparedStatements are useful especially in situations where you can use a for loop or while loop to set a parameter to a succession of values. If you want to execute a Statement object many times, it normally reduces execution time to use a PreparedStatement object instead.
The syntax is straightforward: just insert question marks for any parameters that you'll be substituting before you send the SQL to the database. As with CallableStatements, you need to call close() to make sure database resources are freed as soon as possible. Below is a JDBC Program showing the use of jdbc prepared statements to insert data into tables using jdbc programming.
You need to supply values to be used in place of the question mark placeholders (if there are any) before you can execute a PreparedStatement object. You do this by calling one of the setXXX methods defined in the PreparedStatement class. There is a setXXX method for each primitive type declared in the Java programming language.
PreparedStatement pstmt = con.prepareStatement(
           "update Orders set pname = ? where Prod_Id = ?");
 pstmt.setInt(2, 100);
 pstmt.setString(1, "Bob");
 pstmt.executeUpdate();
An important feature of a PreparedStatement object is that, 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. As a result, the PreparedStatement object contains not just an SQL statement, but an SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement SQL statement without having to compile it first.
Using Prepared Statements in jdbc, objects can be used for SQL statements with no parameters, you probably use them most often for SQL statements that take parameters. The advantage of using SQL statements that take parameters is that you can use the same statement and supply it with different values each time you execute it.

Related Posts Plugin for WordPress, Blogger...
© javabynataraj.blogspot.com from 2009 - 2022. All rights reserved.