Sunday, August 12, 2007

What's the difference between "PreparedStatement" and "Statement"?

PreparedStatements are useful when you have one query to execute several times with just parameters changed. In normal case each and every query has to be checked by database whether syntax is ok or not. SQL Statement are precomplied and stored in PreparedStatement object, so it saves time of database to check its syntax.

  • The PreparedStatement is a slightly more powerful version of a Statement, and should always be at least as quick and easy to handle as a Statement.
    1. Parse the incoming SQL query
    2. Compile the SQL query
    3. Plan/optimize the data acquisition path
    4. Execute the optimized query / acquire and return data
    A Statement will always proceed through the four steps above for each SQL query sent to the database. A PreparedStatement pre-executes steps (1) - (3) in the execution process above. Thus, when creating a PreparedStatement some pre-optimization is performed immediately. The effect is to lessen the load on the database engine at execution time.

    The other strength of the PreparedStatement is that you can use it over and over again with new parameter values, rather than having to create a new Statement object for each new set of parameters. This approach is obviously more efficient, as only one object is created.

    Use the set methods each time to specify new parameter values.




    Where will be the pre executed steps stored, i.e) in Application server or in DataBaseServer

    No comments:

    Topics