Statement vs PreparedStatements which is better in which situation

Hi i read in a few forums and a few articles that PreparedStatement object performs better than the Statement object in situations where a high number of the same sqls are used because it precompiles the sql statement. such as inserting a 1000 employees into a table.
i did the following test and found that the gain for using PreparedStatements is sometimes not a gain but a loss.
What the test basically does is that it inserts an item into the table a 2000 times using both PreparedStatements and Statement objects. And it switches between which object it uses to insert item into the table. So in the end 1000 items would have been inserted using PreparedStatements and 1000 using Statement objects.
Am i doing somthing wrong with my test or is the so called gain by using PreparedStatements a fluke. Please advise.
import java.sql.*;
public class TEST {
    static int Prepcount = 1;
    static long PreptotalTime = 0;
    static long PrepstartTime = 0;
    static long PrependTime = 0;
    static long Prepavarage = 0;
    static int Stmtcount = 1;
    static long StmttotalTime = 0;
    static long StmtstartTime = 0;
    static long StmtendTime = 0;
    static long Stmtavarage = 0;
    static PreparedStatement pst;
    static Statement stmt;
    static ResultSet rs;
    static Connection conn;
    public static void usePrep() {
        try {
            pst = conn.prepareStatement("insert into Dhanu values (?,?)");
            PrepstartTime = System.currentTimeMillis();
            pst.setInt(1, Prepcount);
            pst.setInt(2, Prepcount);
            pst.executeQuery();
            PrependTime = System.currentTimeMillis();
            PreptotalTime = PreptotalTime + (PrependTime - PrepstartTime);
            Prepavarage = PreptotalTime / Prepcount;
            Prepcount++;
            pst.close();
        } catch (Exception e) {
            e.printStackTrace();
    public static void useStatement() {
        try {
            StmtstartTime = System.currentTimeMillis();
            stmt = conn.createStatement();
            rs = stmt.executeQuery("insert into Dhanu values ("+Stmtcount+","+Stmtcount+")");
            StmtendTime = System.currentTimeMillis();
            StmttotalTime = StmttotalTime + (StmtendTime - StmtstartTime);
            Stmtavarage = StmttotalTime / Stmtcount;
            Stmtcount++;
            rs.close();
            stmt.close();
        } catch (Exception e) {
            e.printStackTrace();
    public static void main(String[] args) {
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
            conn = DriverManager.getConnection("jdbc:oracle:thin:@XXX.XXX.XXX.XXX:1521:XXX", "XXX", "XXX");
            System.out.println("Connected to DB");
            conn.setAutoCommit(true);
            for(int x=1;x<=2000;x++){
                if(x%100==0){
                   System.out.println("Count is "+x);
                if(x%2==0){
                    usePrep();
                }else
                    useStatement();
            System.out.println("Prepcount " + Prepcount + " Prepavarage " + Prepavarage + " CurrentExecution " +(PrependTime - PrepstartTime)+ " Totaltime "+PreptotalTime);
            System.out.println("Stmtcount " + Stmtcount + " Stmtavarage " + Stmtavarage+ " CurrentExecution " +(StmtendTime - StmtstartTime)+ " Totaltime "+StmttotalTime);
            System.err.println("Statement time - Prep Time " + (StmttotalTime - PreptotalTime ));
        } catch (Exception ex) {
            ex.printStackTrace();
            System.exit(0);
}

sjasja wrote:
There can still be a performance advantage to PS's even when not used in a loop. Oracle in particular has a textual statement cache. When you execute
insert into foo values(1);
insert into foo values(2);
insert into foo values(3);
the three statements are textually different, so they get re-parsed and the query optimizer runs thrice. But when you prepare
insert into foo values(?);
the parsed and optimized statement remains in the statement cache for some time, and each execution with a different value for "?" can use the pre-parsed statement. The more complex the statement, the bigger the advantage.Yes they do, and so do many others. But it is only that, a cache. It will "usually" be available, not necessarily always. But, in any case, it is still best practice to prepare it, use it multiple times, and close it.
>
I have heard rumors of databases (MSSQL???) where a PS is indeed costlier, as the protocol between the JDBC driver and the DB server requires a separate compilation step. One could argue that in this world, where Java is so important in the server side, and the other advantages of PreparedStatement favor its use, any serious database has had much reason in the last decade to implement a protocol where a separate compilation step is not needed, and any other speed penalties for PSs are decidedly not a marketing advantage.One could argue that, and many have, but PreparedStatements did not spring into being with JDBC, they have existed previously. They are easier to use, however, in Java, and some sort or precompilation is required (even if it is only done the first time the statement is actually run) because at some point in time the DB must determine the paths to take when actually executing the statement, and that was the purpose behind precompiled statements in the first place, so that that determination is done once, and used multiple times. Otherwise it is done as the statement is executed, each time a statement is executed (unless, at least in Oracle, the same statement is still in the statement cache, then it is also reused, rather than redetermined).

Similar Messages

  • Statement and PreparedStatement which is better?

    There are two method to getting data from the database which is:
    1. Statement stmt=con.createStatement();
    rs=stmt.executeQuery("select name from table where id='"+X+"' and yr='"+ year +"'");
    2. PreparedStatement ps = con.prepareStatement("select name from table where id=? and yr=?);
    ps.setString(1, X);
    ps.setString(2, year);
    rs = ps.executeQuery();
    Both method can get the same result. However can anyone tell me that which method 's performance is better or the same? Under the condition that both statement are NOT used in a loop.

    Well the prepared statement does have another advantage: you don't have to think about the format of a date literal. When you put together the SQL for a normal Statement you must somehow create a date literal. With Oracle for example you need to make sure you either use it with the to_date() function or set the session date format beforehand, or rely on the setting of the server (you see: many pitfalls). And no, java.sql.Date does not handle that correctly. The same goes for Timestamp and probably numeric values as well (decimal point vs. decimal comma)
    If you use a PreparedStatement the driver handles this problem for you. So if you want your app to be portable across different DBMS I would go for a PreparedStatement.
    Thomas

  • SSIS The parameterized sql statement yields metadata which does not match the main SQL statement

    Hi all,
    I'm getting the above error when trying to execute a custom lookup.  What I'm trying to do is lookup the minimum promotional price between date ranges.  The SQL executes fine in SSMS
    SELECT refTable.PRICE
    FROM ( SELECT MIN(PRICE) AS PRICE ,
    NAME ,
    ITEMRELATION ,
    FROMDATE ,
    TODATE
    FROM [dbo].[AllCustPrices]
    GROUP BY NAME ,
    ITEMRELATION ,
    FROMDATE ,
    TODATE
    ) [refTable]
    WHERE [refTable].[NAME] = ?
    AND [refTable].[ITEMRELATION] = ?
    AND ? BETWEEN [refTable].[FROMDATE]
    AND [refTable].[TODATE]
    but errors in SSIS?

    Apologies, totally forgot i posted a question on here.  I still haven't resolved this.  full error text is TITLE: Package Validation Error
    Package Validation Error
    ADDITIONAL INFORMATION:
    Error at Data Flow Task [Lookup MIN Price [440]]: The parameterized SQL statement yields metadata which does not match the main SQL statement.
    Error at Data Flow Task [SSIS.Pipeline]: "Lookup MIN Price" failed validation and returned validation status "VS_ISBROKEN".
    Error at Data Flow Task [SSIS.Pipeline]: One or more component failed validation.
    Error at Data Flow Task: There were errors during task validation.
     (Microsoft.DataTransformationServices.VsIntegration)
    BUTTONS:
    OK
    If I take off the MIN function and just put * SSIS is quite happy, it does not like MIN for some reason?
    I'm really stumped with this... checked metadata for third parameter which is W/C Date DT_DBTIMESTAMP which is same as FROMDATE, TODATE where i'm using BETWEEN...

  • Advantages of Statement over PreparedStatement

    I would like to know advantages of Statement over PreparedStatement. If we have PreparedStatement which uses pre-compiled sql statements then why we use Statement.
    Regards,
    Nikhil Shah

    Nikhl_Shah,
    It is important to know the differences, it is also important to know that 99.9% of the time you should use PreparedStatement. Since this has been discussed 100's if not 1000's of times in this forum, first try searching this forum, I would be stunned if you didn't find all the information you need, but if you don't, ask again in this thread and I or others would be happy to list them for perhaps the 1001 time!

  • In which situation I need to active objects after transport

    Hi Experts,
        I'm wondering in which situation I need to active object after transport?  In some cases, I have to active transformation, DTP, infoobject, multiprovider....  Does any one make a conclusion of that?
        thanks in advance.
    Eric

    Sometimes, because of impact of a transport some other objects will be deactivated, then we need to manuaaly activate the objects after transport.
    Also, sometimes transport after import process could not be able to activate the objects, then also we have to activate them manually.
    Or suppose, you have moved and infoobject, due to which some other objects become inactive (where ever infoobjects is being used), then we have to activate them manually, if you dont want to transport them.

  • What is the different between statement and preparedstatement?

    hi,
    recently i have attended a telephonic interview. they asked me what is the different between statement and preparedstatement? and when u will use them? Hi! can any one say me the original difference??

    sorry dear,
    i am already shortlisted. and monday is my HR round.
    . Every 1 is not like u.
    So you have read the examples and explanations that you found when you googled, and you have read the javadoc and you still don't understand? And you are shortlisted? For what? I hope you won't do server programming.
    I will give you a few hints.
    Escaping of data
    Storing of dates
    Safer
    Faster

  • In which situations we should use Character Mode Reports?

    Question: In which situations we should use Character Mode Reports?
    Explaination: I am faced with a certain situation. I feel that I should develop reports in Character Mode. But I am not sure about this.
    I invite all readers to contribute on the subject matter. Once I receive responses, I will explain my specific situation as writing it now may narrow the list of such situations.
    Also I would like to know what problems we face when developing reports in Character Mode. I was developing my first Character Mode report and I faced layering problems. So I would like to know more such precautions.
    TIA
    Tariq

    Hi Muhammad,
    There's any number of cases for using character mode Reports. However, they all typically come down to what your doing with the output of the report.
    Basically, you need character mode reports whenever the Report output needs to be read by some sort of Ascii file reader. This could be notepad, VI, MSVC, dot matrix or fixed character set printers, ...
    A less common case is where you just want to get at the data within the report. You're just using the ascii output as a data dump to pass through to another program/utility. (This is really just a specialised case of the previous one).
    There are some cases where character mode output may be one of several choices. Eg: the body of an email message which could be HTML or plain text.
    Robin.

  • Which situation should we use the text item with the item category TATX

    Dear experts!
    Thank you for your attention!
    I am confused with text item (TATX).
    which situation should we use the text item with the item category TATX????
    Someone told me that the text item is dummy and should be used as a manual of certain standard item. But the manual may be a book or several papers and it also takes up some inventory not a dummy.
    So, could some body tell me what the text item (TATX) exact is and what function it has.
    Best regard!
    Tangdark

    Hi,
    you can use TATX if you like to enter a text and to print some information between the item lines.
    Regards
    William

  • In which situation we will us e BAPI and IDOCS

    Hi friends,
    pls explain in which situation we will us e BAPI & IDOC, why ?
    Regards
    Jagadeeshwar.B

    Hi,
    Both are used for data transfer.
    BAPIS are interfaces which enables to communicate with sap aswellas nonsap systems. IDOCS are intermediate documents sent between sap and nonsap systems.
    BAPIs are a subset of the RFC-enabled function modules, especially designed as Application Programming Interface (API) to the SAP business object, or in other words: are function modules officially released by SAP to be called from external programs.
    IDocs are text encoded documents with a rigid structure that are used to exchange data between R/3 and a foreign system. Instead of calling a program in the destination system directly, the data is first packed into an IDoc and then sent to the receiving system, where it is analyzed and properly processed. Therefore an IDoc data exchange is always an asynchronous process. The significant difference between simple RFC-calls and IDoc data exchange is the fact, that every action performed on IDocs are protocolled by R/3 and IDocs can be reprocessed if an error occurred in one of the message steps.
    But BAPIs are synchronous ( i.e. the systems must be online) whereas IDOCS are synchronous ( ie. both systems need not be online .
    we can make bapis asynchronous using the IDOCS.
    thanks and regards.

  • Using an SQL statement... which would have better performance ???

    Hi i have to update a table for like 1000, 2000 items..normally this takes around....50-55 minutes...the way we are doing is like using a For loop and traversing for each item which has to be updated...
    eg :- for (i=0; i<n;i++)
    (update item_table set XXXXXXXXXXX where item_id=item)
    i want to know would it be more efficient to just run one single update command... like ...
    update item_table set XXXXXXXXXX where item_id in (item1,item2,................)
    since the changes done are the same for all the items.
    Thanks

    It would be efficient because it will save the trips to the database that are currently happening in the loop. The downside is that you may not be able to add as many elements to the IN clause because databases have some limit to the set of values you could specify in the IN clause.
    I would recommend using batches of items in manageable sizes (like 200 or so) and use the batch update facility provided in JDBC.
    http://java.sun.com/developer/onlineTraining/Database/JDBC20Intro/JDBC20.html#JDBC2015

  • Many AM State Passivation occurs , which AM Pool Parameters to tune ?

    Hi All,
    Our ADF faces+BC 10.1.3.3 (on OAS 10.1.3.3) application is going live, and we are in performance tuning stage now.
    On peak load, the application get very slow, and we run the AWR/statspack on database side to see whats going on database side.
    Among many queries to tune, I see that within 50 minutes, there are 29,850 "Insert Into PS_TXN .." statement get executed.
    That means a lot of state passivation occurs.
    Here is the value of AM Parameters : (others parameter left unchanged)
    Initial Pool Size = 0
    Max Pool Size = 5000
    Referenced Pool Size = 10
    Minimum Available Size = 25
    Maximum Available Size = 90
    The concurrent user that access the particular AM on peak is approx. 100
    Is the any parameter that I can tune to reduce the passivation ?
    Thank you very much,
    xtanto

    See 29.6.1 Pool Behavior Parameters and study the jbo.dofailover
    If you have set that property to true, you will do a passivation on every request for every user session.
    See 29.6.2 Pool Sizing Parameters.
    Assuming that you are not using the jbo.dofailover (which would be the default to not be using it), then large numbers of passivations/activiations indicate that the reference pool size is too small for the average number of simultaneously active user sessions that you need to support.
    If you have it set to 10, it means that only ten user sessions will be allowed to try and "rendezvous" with the same AM instance they were using last time.

  • Uploading credit card statement for USD which is not the local currency.

    Hello Experts,
    Please let me know is it possible to upload a credit card statement to showup in document buffer for USD, given that USD is not the local currency of the company code for which we are uploading the statement.
    Regards,
    Vijay

    Hi,
    For uploading the credit card statement we will use std function  module HR_TRV_CREDIT_CARD_CLEARING. This function module will not allow to upload the credit card expenses other than the company code currency (accounting currency). However you can modify the function module according to your requirement.
    Thanks,
    Nandagopal C

  • Statements/Commands for which we cannot reply on Sy-subrc

    Hi experts,
    can any one give me the list of statements/copmmands that we cannot rely on sy-subrc

    when u are working on app server filed Transfer stmt. does not revert back with sy-subrc

  • Find perform statement in MB1B which is calling Form statement in Zprogram

    Hi,
    we written form statement in zprogram, it is called in MB1B transaction.this linked
    to one output type.my problem is how to find  perform statement in MB1B.
    Do help at earliest.
    Thanks in advance.
    Rama.
    SAP-Techincal consultant.

    Thanks for reply.
    in zprogram we have been updating ztables.problem here is even we set break point here, cursor  not coming into that subroutine when we run transaction MB1B.
    CAN U PLZ say how to stop execution in subroutine.
    YOURS
    RAM

  • Select statement from tables which have now been split

    I used to select from 3 tables:
    user, login, location
    I would do:
    select distinct user.id, login.computer_id, location.id as location_id
    from user, login, location
    where user.id = login.user_id
    and login.location_id = location.id
    and user.id = "manny"
    but user has now been split into user1, and user2
    I want to pull data where it exists from user1 or user2.
    Much of the data in user1 is duplicated in user2 and vice versa, but I want to pull only one instance where it appears so that I can still get single row results of:
    ID COMPUTER_ID LOCATION_ID
    mannyd redstar_1 Bronx, NY
    Any ideas on the query?

    Why would you split a single table into multiple tables with the same structure and much of the same data? That seems rather counterproductive.
    I suppose you could do something like
    select user.id, login.computer_id, location.id as location_id
    from user1 user, login, location
    where user.id = login.user_id
    and login.location_id = location.id
    and user.id = 'manny'
    UNION
    select user.id, login.computer_id, location.id as location_id
    from user2 user, login, location
    where user.id = login.user_id
    and login.location_id = location.id
    and user.id = 'manny'but that's obviously going to be much more expensive than the single-table approach...
    Justin

Maybe you are looking for