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

Similar Messages

  • 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).

  • If i do a lot of writing, web surfing and email, which is better for me, macbook pro or air?

    looking for the right portable as a gift for someone who does a LOT of writing and also email and websurfing and research. which is better, the macbook pro or the air?

    Either one.

  • 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

  • Battery charging by usb port on PC and adapter which is better

    Please help me
    Battery charging by usb port on PC and adapter (enclosed with IPHONE box )which is better?
    Regards

    Adapter is probably quicker as you have slightly better power than from a USB socket

  • Hesitate with Statement and PreparedStatement!!!!!!

    i create a test to make clear the 2 thing's diffrience,
    Test use tomcat4.1.24+mysql,test times more than 15 per test
    situation:
    1:create a Connection to mysql,create a Statement object, use this Statement object to query a sql,use time for 411ms;
    2:create a Connection to mysql,create a PreparedStatement object, use this PreparedStatement object to query a sql with a parameter,use time for 409ms;
    3:create a Connection and a Statement to mysql in the construction method,in the method to query a sql use the current Statement,use time 380 ms;
    4:create a Connection and a PreparedStatement to mysql in the construction method,in the method to query a sql use the current PreparedStatement ,use time 390 ms;
    5:jstl:<sql:setDataSource/>set the scope with the four parameter in (request,page,session,application),use time is all about 411ms;
    so i wanna anybody tell me ,what is the advantage of PreparedStatement.

    A PreparedStatement means you don't have to do anything special if you try to insert a string that contains a quote character. And you don't have to tie your code in knots trying to get your timestamps formatted in just the way your database insists on. The PreparedStatement handles all those issues for you. The Statement doesn't.
    A more realistic benchmark comparison would be:
    1. Create a Connection, create a PreparedStatement, use it as a query 1000 times.
    2. Create a Connection, then 1000 times create a Statement and use it as a query.
    PC&#178;

  • Can some explain 1080i and 1080p which is better for a pal project in HD

    I am new with these type of codec, plus which one is better for a pal projects not NTSC. Also I want to know if there would be any problems when I take a project that is done in Pal and move it to NTSC would there be some frame problems.
    thanks

    I like the p footage better because it looks more like film, plays better on the computer, and looks better in web streams... as far as going to NTSC in the end, Compressor's "advanced format conversions" or Graeme Nattress' Standards converter does a fine job of PAL to NTSC... Edit in the native format you've shot though, then in the end do the standards conversion. You needn't worry about anything special here...
    Jerry

  • Jsf and applete-which is better to use to design recruitment intranet

    Hi,
    I'm interested in enhancing my skills on developing standard interface for my company.
    Pls, Is it possible to design standard interface like the ones in accounting software with jsf. Or is better to use appletes
    Emeka

    Here's a sample:
    Global Variables
        * Define structure for internal table
        TYPES: BEGIN OF ty_zsd_ds03,
                   doc_number TYPE /bi0/oidoc_number,
                   fiscvarnt TYPE /bi0/oifiscvarnt,
                   ord_reason TYPE /bi0/oiord_reason,
               END OF ty_zsd_ds03.
        * Define internal table
        DATA: t_zsd_ds03 TYPE SORTED TABLE OF ty_zsd_ds03
                  WITH NON-UNIQUE KEY doc_number fiscvarnt.
        * Define work area
        DATA: wa_zsd_ds03 TYPE ty_zsd_ds03.
    Start Routine
        SELECT
            doc_number
            fiscvarnt
            ord_reason
        FROM
            /bic/azsd_ds0300
        INTO TABLE
            t_zsd_ds03
        FOR
            ALL ENTRIES IN source_package
        WHERE
            doc_number = source_package-doc_number
            and fiscvarnt = source_package-fiscvarnt.
        DELETE
            ADJACENT DUPLICATES
        FROM
            t_zsd_ds03
        COMPARING
            doc_number
            fiscvarnt.
    Characteristic Routine
        READ TABLE
            t_zsd_ds03
        INTO
            wa_zsd_ds03
        WITH TABLE KEY
            doc_number = source_fields-doc_number
            fiscvarnt = source_fields-fiscvarnt.
        IF sy-subrc EQ 0.
            result = wa_zsd_ds03-ord_reason.
        ELSE.
            CLEAR result.
        ENDIF.
    If you have multiple targets, then do the READ TABLE statement inside the LOOP AT results_package ASSIGNING <result_fields> statement. If it's successfuly, then you'd populate the wa_zsd_ds03-field, in this example, into <result_fields>-field if successful or CLEAR (initialize) the value in <result_fields>-field.

  • What is the difference between Statement and PreparedStatement

    Hi
    What is the difference between Stement and PrepareStatement Other than PreCompilation and dynamic Parameters?
    Thanks in advance.
    Sekhar

    Most of the differences are either those, or consequences of those (such as better performance, greater security, and simpler use for PreparedStatement). Serious programmers should almost always use PreparedStatement.
    The only other thing I know of is trivial: you can get ResultSetMetaData from a PreparedStatement without actually executing a query.

  • Difference between Statement and PreparedStatement

    Hi All,
    according to jdk doc
    A SQL statement is precompiled and stored in a PreparedStatement object. This object can then be used to efficiently execute this statement multiple times.
    where exactly statement is precompiled?
    Vinay

    The compiled statement is stored in Oracle's data dictionary. If you have permissions, you can view this information by SELECTing from V$SQL or V$SQLAREA. Hope this helps.

  • Comparing JSP and JSF, which 1 better?

    Currently i need to run a new project. Now i need to choosing 1 of the language to coding my project. Which 1 is better to use?
    In this project i have to include the web page that using JSP scriptlet to code because this project is create a dynamic menu to link up all web application. Is the JSF can link to JSP and JSP can link back to JSF?

    Welcome to SCN.
    Please read forum rules (you'll see that you must search the forum first (your question is already answered))

  • Need either a macbook or ipad, primarily for photos and browsing, which is better?

    Apple geniuses are split between whether I would need a macbook or if an Ipad would work for my use.  Primary uses: browsing, email, editing photos, and listeming to music.
    Thanks,
    Jenelle

    jenellefromcharlotte wrote:
      Primary uses: browsing, email, editing photos, and listeming to music.
    You want a computer if you're seriously into editing photos. While there are some editing programs that run on the iPad...Filterstorm, as an example...none compare to Photoshop which only runs on a computer. Adobe has released a Photoshop program for the iPad, but IMO, its not ready for prime time. The iPad augments the computer for serious photo work...quick edits in the field...not having to lug around a laptop, but you need the storage & power of a computer for serious work.

  • What is different between asp and jsp, which is better and why

    hi, i would like to know which script language is better (ASP or JSP). if you can give me a detail comparison. Thank in advance
    zhe

    What do you expect small-time loser?

  • Problem of Statement and PreparedStatement

    hi
    The PreparedStatement has a metod :
    setNull(int parameterIndex, int sqlType)
    I want make a class to simulate PreparedStatement.
    String sql = "update tablename custname = ?,orderdate = ? where id = ?";
    mySimulate = new mySimulate(sql);
    mySimulate.setString(1,"myName");
    mySimulate.setNull(2,null);
    mySimulate.setInt(3,1);
    Statement st = con.createStatement() ;
    st.executeQuery(mySimulate.toString())
    now i don't know how to simulate the method of setNull(),setObject(),setTime()

    This isn't so easy because the SQL that gets returned will depend on the database you're using.
    However, I would implement this by tokenising the original SQL string using '?' as a delimiter.
    This would give you a list of SQL fragments.
    You would then need another list of SQL values that gets populated when the setXXX methods are called. Finally you would interleave the two lists to form the finished string:
    public class MySimulate
      protected static final SimpleDateFormat SQL_DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy"); // Or whatever format your database accepts
      protected static final String NULL = "NVL"; // Or whatever your database accepts for null value
      protected String[] clauses;
      protected String[] values;
      public MySimulate(String sql)
        StringTokenizer st = new StringTokenizer(sql, "?", false);
        clauses = new String[st.getTokenCount()];
        values = new String[clauses.length];
        for(int idx = 0; idx < clauses.length; idx++)
          clauses[idx] = st.nextToken();
      public void setString(int idx, String str)
        // Should replace all occurrences of ' with '' first!
        values[idx] = "'" + str + "'";
      public void setDate(int idx, Date date)
        values[idx] = SQL_DATE_FORMAT.format(date);
      public void setNull(int idx)
        values[idx] = NULL;
      public void setInt(int idx, int val)
        values[idx] = String.valueOf(val);
      public String toString()
        StringBuffer b = new StringBuffer();
        for(int idx = 0; idx < clauses.length; idx++)
          b.append(clauses[idx]);
          b.append(values[idx]);
        return b.toString();
    }Something like that anyway.
    You'll have to play around with how to format your dates, escaping quotes in string values etc. You might even want to make it configurable for different databases.
    Hope it helps, though!

  • When comparing scripts and smartforms which is better

    hi can you please help out the advantages and disadvantages of scripts and smartforms

    Welcome to SCN.
    Please read forum rules (you'll see that you must search the forum first (your question is already answered))

Maybe you are looking for

  • How to identify which drive is the current boot drive?

    I have a PowerBook running Leopard, and I prefer to boot from the external drive. It's bigger and has my working files. The current internal drive is for future use, for when I have a replacement machine. I know how to specify the boot drive in Prefe

  • Sorting measures (calculated members) in SSAS cube designer

    Hi, In SSAS 2012 cube designer, on the "Calculations" tab I am writing some simple calculated members and displaying it in a folder (Display Folder=) FolderA am So this FolderA has the members as below : [<-A1], [-A1], [A], [A1], [A2], [A3], [A4], [A

  • How to unlock without a keypad

    I have a blackberry curve 8320 and the keypad broke, so it's now impossible to unlock it or even reset it because i cannot write all the letters needed. how do i reset it or unlock it without the keypad?

  • HT4479 do you need to put bank details in

    do you need to put bank details in

  • Hyperlinks within scrollable frames

    I'm trying to get hyperlinks within a scrollable text frame to work but it's not working properly in the content viewer. Is it possible to do them within scrollable content, and if so, is there a certain technique that works best? Thanks!