PreparedStatement vs. Statement

Is PreparedStatement always better than Statement?
My idea is, PreparedStatement is more efficient when in a loop. (Is this correct?)
But when I read some code, the author always uses PreparedStatement, as if it is preferred no matter what.
Can you let me know if there are differences? Thanks!

While there are certainly times to use Statement, beginners should always start with PreparedStatement, using bind variables.
With Oracle and many other databases, PreparedStatement with bind variables will give you improved perfromance on subsequent execution of the SQL (as long as it's an EXACT string match), even when the following executions are hours, minutes, or even days later, even by a different program. This benefit comes from the database caching the execution plan for the SQL. The execution plan is the result of parsing and evaluating the SQL and is somewhat analogous to compiling a program file. Just as you don't want to compile every time you execute a program, so you also don't want to parse and evaluate every time you submit a SQL statement. Bind variables in PreparedStatements helps you do that.
The variability on how long the database will cache your execution plan comes from the fact that the cache is a fixed size LRU (least recently used) cache. SQL that is used infrequently ages out of the cache and how frequently depends on how much different SQL gets seen by the different database. SQL is "different" if it's not an exact string match (including case and any non-bound data values embedded in it) to something already in the cache. This means that using bind variables with PreparedStatement not only tends to speed up performance for that SQL, it also helps to improve performance on busy databases for everything else by reducing the amount of "different" SQL, thereby increasing the length of time other infrequently used SQL stays in the cache, and thereby improving the cache hit ratio on this LRU cache.
Additionally, PreparedStatement with bind variables helps prevent "SQL injection" attacks, a significant problem of naively programmed web sites. Search the web for detailed explanations, there's plenty of them.
Finally, PreparedStatement with bind variables can make your life easier. Many beginners try to code dynamically built SQL, such as:
String sql = "SELECT * FROM user_data WHERE last_name = '" + lastName + "'";Ignoring SQL injection attacks, that works OK until:
String lastName = "O'Conner";The quote embedded in the name gets matched to first quote after the = in the SQL, and the SQL is broken upon execution. You either need to check all your data to see if it needs to haven embedded quotes escaped, or you use PreparedStatement and bind variables.
There are some SQL statements where, as far as I know, it doesn't matter much, e.g. DDL statements (table creation and the like) and connection altering statements, such as "ALTER SESSION SET NLS_DATE_FORMAT = 'YYYYMMDD HH24:MI'". I'm not sure either is cached, or if caching has any benefit; even if it is and there is, the SQL doesn't vary...
There are some very very rare times when (at least on Oracle), using a bind variable can increase the execution time for some values of the variable; the problem is very rare and is almost always caused by data skew; for most values of that bind variable, the correct thing to do is scan all the data in the table, but for a very few values, the correct thing is to use an index to look up the needed rows. When bind variables are used for that variable, the execution for the "typical" case is picked; if the SQL has the bind variable replaced with an actual value, the optimizer can see that for those few particular values, the index lookup is faster and will use that. This data skew problem commonly comes up with "job status" flags on tables that hold both "in progress" and "completed" jobs. Eventually, the "completed" jobs are 99.99 percent of the data, and find the non-completed ones gets slower than it should be.
Beginners should use PreparedStatements until they understand the exceptions or run into performance problems.

Similar Messages

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

    What's the difference between "PreparedStatement" and "Statement"?
    Which is better??????

    Read the docs for the two classes. The differences are apparent there.
    Which one is better depends on your needs. I think that constructing and executing a PreparedStatement can be a bit less performant than just a Statement, if you're only executing the query one time. But I don't think that difference will normally be noticable in the context of a given application.
    Additionally, if you have to pass any dates or strings to the query, you'll want PreparedStatement's parameters, rather than trying to format and escape things in the query string.

  • PreparedStatement vs Statement - When executing only once

    Are there any performance implications in using PreparedStatement vs
    Statement when you are executing the SQL only once? I am talking about all
    kinds of SQL (Select, Update, Insert and Delete). If PrepatedStatement is
    used, I would expect some overhead in setting values for different columns
    separately and precompliling. Is that overhead significant enough to
    degrade performance? If we execute statement only once, I do not expect to
    any gain on performance.
    I would appreciate any comments.
    Sarat

    It also depends on the database/driver combination,several database can be
    configured to maintain a prepared statement cache at the DB level (I have
    never done it myself, but I know people who has done this. Lately I use
    mostly Oracle, for which I should not be configured an expert :)).
    Also the weblogic's prepared statement cache only caches first so many
    statements. If you have used them all up at the startup you are out of luck.
    I know you already knew that, but may be helpful to the original poster.
    .raja
    "Cameron Purdy" <[email protected]> wrote in message
    news:[email protected]..
    BTW - there is a case where prepped stmts are faster -- when they arecached
    by Weblogic's jdbc wrappers. So my previous answer can be wrong.
    Peace,
    Cameron Purdy
    Tangosol Inc.
    << Tangosol Server: How Weblogic applications are customized >>
    << Download now from http://www.tangosol.com/download.jsp >>
    "sarat" <[email protected]> wrote in message
    news:3b715901$[email protected]..
    Are there any performance implications in using PreparedStatement vs
    Statement when you are executing the SQL only once? I am talking aboutall
    kinds of SQL (Select, Update, Insert and Delete). If PrepatedStatement
    is
    used, I would expect some overhead in setting values for differentcolumns
    separately and precompliling. Is that overhead significant enough to
    degrade performance? If we execute statement only once, I do not expectto
    any gain on performance.
    I would appreciate any comments.
    Sarat

  • PreparedStatement & regular Statement - different results for same select

    I was wondering if someone could either
    i) try this out for me to confirm my results or
    ii) let me know what I am doing wrong
    I'm one of the developers on a product and am currently investigating localization for the Thai language...just checking to see that Java and Swing have no problems with it. The only bewildering thing which has happened is noticing that some values which are fetched from the database display in Thai perfectly and other values display as a garble. Sometimes the exact same column is displayed correctly in one part of the program but is not OK in another part. I think I've figured out what it going on and suspect a bug in Oracle's JDBC:
    Some selects were configured as PreparedStatements and those return the Thai properly. The more common case however was for programmers to use a simple Statement object for their select and it is in those that the multi-byte strings don't get returned properly.
    The following code shows the problem that I am experiencing. I am basically executing the exact same select in 2 different ways and they are both giving different results as long as the column being queried contains a Thai character. If someone could grab and check it out and let me know if they see the same thing, I'd appreciate it. Just change the column/table name and the username/password/databaseIP to get it to run.
    <code>
    import java.sql.*;
    public class SelectTest {
    public static void main(String[] args) {
    try {
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    Connection conn = DriverManager.getConnection( "jdbc:oracle:thin:@10.4.31.168:1524:ora8",
    "dms_girouard",
    "girouard");
    String sqlCommand = "select C0620_Title from T0620_SwSheet";
    Statement statement = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
    ResultSet.CONCUR_READ_ONLY);
    ResultSet resultSet1 = statement.executeQuery(sqlCommand);
    while (resultSet1.next()) {
    if (resultSet1.getString("C0620_Title") != null) {
    System.out.println("resultSet1 Title = " + resultSet1.getString("C0620_Title"));
    PreparedStatement preparedStatement = conn.prepareStatement(sqlCommand);
    ResultSet resultSet2 = preparedStatement.executeQuery();
    while (resultSet2.next()) {
    if (resultSet2.getString("C0620_Title") != null) {
    System.out.println("resultSet2 Title = " + resultSet2.getString("C0620_Title"));
    catch (Exception e) {
    System.out.println(e.getMessage());
    </code>

    Hi Peter,
    Are you using NCHAR column for Thai , or is your database character set set for Thai.
    If you are using a NCHAR column for holding Thai data, then you have to use the
    OraclePreparedStatement.setFormOfUse(...) before executing the select.
    Regards
    Elango. Hi Elangovan,
    Thank you for answering.
    The datatype on the column is VARCHAR2.
    I did my initial tests without doing anything special to make sure the database is localized for Thai, and I was happy to find that almost everything still worked fine - I was able to save and retrieve Thai strings to the database almost perfectly.
    The only problem I discovered was the difference between Statement and PreparedStatement selects on a column containing Thai. Colleagues of mine have said they see the same thing when testing on a Oracle database which has been configured specifically for the Thai customer.
    I read somewhere that the current JDBC drivers are using an older version of the Unicode standard than the most current version of the Java SDK and that it was causing some problems with Korean. I'm wondering if maybe it's the same problem with Thai.

  • PreparedStatement and Statement

    Hi Joe,
    We are using the Driver provided by Weblogic (jdriver) and not the one from
    Informix.Do you suggest any settings for this
    thanks
    Nirmala.

    Nirmala,
    Which version of Weblogic do you use?
    Regards,
    Slava Imeshev
    "Nirmala" <[email protected]> wrote in message
    news:3bcc9ff7$[email protected]..
    >
    Hi
    public void ejbLoad () throws RemoteException, NoSuchEntityException {
    Connection connection = null;//JDBC Connection from the pool
    PreparedStatement ps = null; // SQL query statement
    Statement statement = null;
    ResultSet rs = null; // JDBC result set
    try {
    // Obtain a connection from the connection pool.
    ID = (String) context.getPrimaryKey ();
    connection = DatabaseHelper.getConnection ();
    // Our SQL query.
    // Make sure to upshift the user id.
    String sqlQuery =
    "SELECT * from customer WHERE id= ?";
    long startTime = System.currentTimeMillis();
    ps = connection.prepareStatement(sqlQuery);
    ps.setString(1,ID.toUpperCase());
    // Read the customer data from the database.
    rs = ps.executeQuery ();
    long endTime = System.currentTimeMillis();
    long total = endTime -startTime;
    System.out.println("total time taken1 " +CISSLogger.getTimeInSeconds(total));
    >
    >
    // rs = ps.getResultSet();
    Above is the snippet of the code we are using in ejbLoad,
    Appreciate your suggestion
    thanks
    Nirmala.
    "Slava Imeshev" <[email protected]> wrote:
    Hi Nirmala,
    Could you give us a fragment of your code that uses PreparedStatement?
    Regards,
    Slava Imeshev
    "Nirmala" <[email protected]> wrote in message
    news:3bcc8772$[email protected]..
    Hi Joe,
    We are using the Driver provided by Weblogic (jdriver) and not theone
    from
    Informix.Do you suggest any settings for this
    thanks
    Nirmala.

  • PreparedStatement vs Statement & OCI vs thin

    http://www.oreilly.com/catalog/jorajdbc/chapter/ch19.html
    came accross this sample chapter from a book which compares Statement vs PreparedStatement vs CallableStatement (and all of the aforementioned using both the thin and OCI drivers for Oracle)
    Just wondering if anyone had read the book. It was published in Dec 2001 so the results should be current. If anyone has read it, let me know what you think.
    I haven't found many reliable benchmarks for database access, but this one compares only Oracle implementations so I have to assume that it is unbiased. (not the usual "my drivers are better than my competitions - benchmarks to prove it"... then you check out the competition and it says "my drivers are the fastest - benchmarks to prove it!")
    Jamie

    I haven't read this book, but from other sources and my own experience the basic rules are as follows:
    - PreparedStatement is faster then Statement if the SQL statemtn is rather complex and used frequently
    - OCI is generally faster than Thin, but requires more setup on the client
    as always, these rules have exceptions, and the only way to find out is to try with your program.

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

  • Statement vs PreparedStatement

    Can anyone offer guidelines ( or point me to documentation) which describes when/why use a
    Statement as opposed to a PreparedStatement.
    I realize that a PreparedStatement can be defined with Bind variables for later substitution and thus the statement gets compiled only once thereby being more efficient.
    But is that the only difference ? does it make sense to use a PreparedStatement even if there are no Bind variables ?

    Whenever you want to re-use a statement you should use Statement and not PreparedStatement.
    Statements can effectively only be used once, since you provide the SQL text to the execute method: this means that when issuing execute (or executeQuery) the statement is always fully reparsed by the database.
    If you have a PreparedStatement object, you can re-execute it, and the database will reuse the parsed statement.

  • How to insert an image file as blob using JDBC Statement

    Hi,
    I'm new on java.
    I want the code to insert an image file in Oracle database whose data type is blob.
    i want to use JDBC statement not the prepared statement.
    Please help me out.

    user8739226 wrote:
    thanks for the solution.
    I want to ask one thing
    let say i've created a method in a bean in which i'm passing three parameters.
    One is tablename as String, Second is Name of tablefields as Object, Third is Values as Object
    Like:
    public synchronized int insert(String table,Object[] fields, Object[] values)Ah now we're getting somewhere. I was trying to come up with a situation where using a regular Statement over PreparedStatement would be viable and came up with practically nothing.
    In the method body i'm accessing the table fields and values and combining them into the insert sql query.
    how can i do this using preparedstatment.
    how do i come to know here in this bean that this value is int or string or date at runtime to use setInt, setString, setdate or setBlob respectively.That's your problem. Bad design. You want to make some sort of universal insert method that can insert anything anywhere. But it doesn't really make sense, because whenever you're trying to insert something, you know exactly what you want to insert and where. You could use a PreparedStatement at that point (although encapsulate it in its own method). Now you're trying to create your own poorly designed framework over JDBC that doesn't solve problems, only increases them.
    Above was the only reason i saw, i was using statement instead of preparedstatment as statement was looking easy in this situation.
    please, give me the solution of above using preparedstatment.No, rather you should reconsider your design. What advantage does your insert() method give you over, let's say using a regular PreparedStatement. Granted, you can put your connection opening and other boilerplate code in the method. But if that's your only problem, then your insert method isn't gonna be much use. You could always switch to JPA for example and work with that.

  • Unable to set string in prepared statement

    Hi all,
    I just want to set an string to a prepared stmt.
    the setting string is in the format..... the integers with comma saparated....
    str="23,55,22"
    ps.setString(1,str)
    The prepare statement is taking only the first integer... i.e. 23
    can any one help me out..........
    thanks in advance,
    prakhyath

    if i am not mistaken.... If I create the Prepared
    Statement after receiving the arguments that are to
    be provided to it.... the actual purpose.. Of using
    a prepared statement is not served at all....Not creating a new Statement each time, is only one of the purposes of PreparedStatement. In this case, since the arguments should be ints (and I hope you are checking that), then it doesn't make much of a difference. But a PreparedStatement is alos used to easily facilitate the proper quoting and escaping of the parameters set, which almost eliminates any chance of an SQL injection attack. There are also a few other convienences associated with a PreparedStatement, but, in this case, you are probabyl right in that there is no advantage of PreparedStatement over Statement (as long as you are checking that the arguments provided are actually ints, otherwise you are opening yourself up to an injection attack).

  • Diff b/n CreateStatement and PreparedStatement

    Difference Between CreateStatement and PrepareStatement
    Which one is Better Performance and why?

    Please stop asking about performance in all your questions. There is MUCH more than performance to consider.
    createStatement returns a Statement object.
    prepareStatement returns a PreparedStatement object.
    For reasons including code portability, resolution of data type formatting issues and security it is better to choose PreparedStatement over Statement.
    Under some conditions the use of a PreparedStatement will result in better performance, under other conditions the use of Statement will result in better performance. No I will not expand on this because it is not relevent. It is better for you use to PreparedStatement for the reasons listed above and those for your purposes outweigh any performance differences.
    Questions regarding Statement vs PreparedStatement have been asked and answered repeatedly in this forum. If you have more question do a search and you will find the answers. You should consider searching on a more regular basis anyway as all your questions are easily answered by searching as all of them have been asked before.

  • Statement,Prepared Statement and callable statement

    Hi,
    Please let me know in which scenario we are using Statement,Prepared Statement and callable statement.
    and which is efficient one among the above.
    Thanks in advance

    Welcome to the forum!
    >
    Please let me know in which scenario we are using Statement,Prepared Statement and callable statement.
    >
    We don't know what scenario you are using those in or if you are using them at all. Are you asking what they are?
    For document related questions you should consult the documentation or use your favorite search engine to get information.
    See the Java Tutorial
    http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
    >
    The main feature of a PreparedStatement object is that, unlike a Statement object, it is given a SQL statement when it is created. The advantage to this is that in most cases, this SQL statement is sent to the DBMS right away, where it is compiled. As a result, the PreparedStatement object contains not just a SQL statement, but a 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.
    >
    The Javadocs for your Java SDK have the API for each of those classes and a description of what they are. And the Oracle JDBC Developer Guide has extensive information on how to use them.
    http://docs.oracle.com/cd/B28359_01/java.111/b31224/toc.htm

  • Inspecting sql_query in PreparedStatement

    When executing code in debug mode in JDeveloper, it's nice to use the Inspect feature.
    My problem is this: I've set a break in a method that has been passed a PreparedStatement (and nothing else).
    Using the inspector, I can see that one of the class variables is sql_query, and it's set to the string that the PreparedStatement class compiled. But why I can't see that same variable programatically? It doesn't seem to be in the PreparedStatement or Statement source code. It would be really nice to print the sql string on a catch if anything goes wrong. Anyone have any suggestions?

    Please enclose your output within tag so that people here can read it easily and help you. Also the reason that why you want to remove rowid?
    Salman
    Edited by: Salman Qureshi on Mar 20, 2013 3:53 PM                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Ouput sql from prepared statement

    I'm using prepared statements and I want to output the sql that is being run in the statement to the console. For example:
    Class.forName("oracle.jdbc.driver.OracleDriver");
    conn = DriverManager.getConnection("jdbc:oracle:thin:@xx.xx.x.xx:xxxx:xxxx", "xxxx", "xxxx");
    stmt = conn.prepareStatement("update table set a = ? where b = ? and c = ?");
    stmt.setString(1, "a");
    stmt.setString(2, "b");
    stmt.setString(3, "c");
    System.out.println(?????????);So the statement would be something like: "update table set a = 'a' where b = 'b' and c = 'c'"
    How can I get the sql from the statement? I would have thought this would be easy but there doesn't seem to be any obvious method.

    I also came across the article about overpowering the PreparedStatement, neat stuff.
    But as I downloaded the classes and compiled them, I got some errors due to the fact that some methods from the PreparedStatement- and Statement-interfaces were not implemented by the DebuggableStatement-class.
    I suspect this has something to do with the JDK-version being used.
    I myself am using version 1.4.1_01-b01.
    Anyone came across this same problem?
    As I do want to compile under the version mentioned, I just insert the method(-stubs) myself. Or is this a bad idea?

  • Why do we need Prepared Statement?

    Why do we need Prepared Statement ? How it is better tha Statement ?
    Why cant we use Callable Statement instead of Prepared Statement?

    Statement is a generic SQL statement you build yourself. PreparedStatement is also a SQL statement; however, the bind variables do not have to be escaped (e.g., you do not need to surround a string with quotes). Another benefit of PreparedStatements is that the JDBC driver can cache them for subsequent re-use, eliminating the parsing step and improving response time. Finally, CallableStatement is to execute a stored procedure, not a SQL statement.
    In general, use PreparedStatement over Statement if possible. Use CallableStatement only for stored procedures.
    - Saish

  • Conceptual question regarding PreparedStatement

    Hi all,
    I wonder what is the different between the following 2 codes:
        public void method1(String[] cityList) throws Exception
             for (int x=0; x<cityList.length; x++)
                  String q="SELECT * FROM table 1 WHERE CITY='"+cityList+"'";
                      Statement stmt = con.createStatement();
                      ResultSet rs = stmt.executeQuery(q);   
                      while (rs.next())
                           //some code here
        public void method2(String[] cityList) throws Exception
                  String q="SELECT * FROM table 1 WHERE CITY=?";
                  PreparedStatement ps = con.prepareStatement(q);
                  for (int x=0; x<cityList.length; x++)
                       ps.setString(1, cityList[x]);
                       ResultSet rs = ps.executeQuery();
                           while (rs.next())
                             //code here  
        }Both return the same result but I guess (and correct me if I�m wrong) that it is better to use the prepared statement (efficiency�but how, why?)
    Thanks for any thoughts

    The efficiency issue is not really PreparedStatement versus Statement, but really "bind variables" (which PreparedStatement supports and Satement doesn't) versus not using bind variables, which you can do with PreparedStatement quite easily, thereby throwing away the performance gain (or working around some exceptional cases).
    An extremely detailed analysis of using bind variables, versus not, for Oracle, using Oracle's PL/SQL language, can be found here:
    http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:2444907911913
    For this example, bind variables were 6 times faster for 1,000 test executions...
    The nutshell explanation of this is:
    1) When a database sees a new SQL statement for the first time, it has to figure out how to execute it. This "figuring out" is called "parsing" and is pretty similar to regular code compilation; resources are looked for, references are resolved, and optimizations are applied. It's not cheap. An execution plan results.
    2) Most good databases will cache the SQL and its execution plan, so that if it sees IDENTICAL sql again, it can reuse the execution plan. Bind variables make the SQL identical when the data values change (many DBs use the hashed SQL as a cache key).
    3) Furthermore, as the Oracle example points out, many databases have to lock internal resources while parsing; such locking drastically inhibits parallel execution in mutli-processor environments. Not using bind variables is a great (and all too common) way to turn a $500,000 database installation into the effective equivalent of a $2,000 database.
    Besides the other poster's ease of use issue for quotes and other things, bind variables also help a lot with application security; Google for "SQL injection attack", or see:
    http://www.oracle.com/technology/oramag/oracle/05-jan/o15asktom.html
    Again, this isn't really a JDBC-specific issue.

Maybe you are looking for

  • Quality Issues with Video Footage

    Hello all I'm not sure if this is the correct forum to post this question I'm having trouble with the quality of my footage on export to DVD and I'm wondering if this is due to my settings in FCP or my workflow. The problem is that I am getting gradi

  • Play All option

    I've been making music videos of my granddaughter's softball team. Each video is a separate iMovie project running three and a half to five minutes, depending on the song I use. I export each video as a QT movie at full quality, then bring these into

  • Php 5.1.2 doesn't seem to recognize the --with-oci8-instant-client option

    I just tried configuring php 5.1.2 with the --with-oci8-instant-client option and could never get phpinfo() to show the oci8 section... Finally went back and tried php 5.1.1 and it worked. If anyone else could verify this behavior, maybe the PHP folk

  • Vendor sub-range in automatic po

    Hi, All, I have a problem with vendor sub-range in the next process: In info record there is sub-range SR1 for material/vendor. In contract there is sub-range SR2 for same material/vendor In mrp was created requisition with reference to contract. we

  • Can I watch a project's finished video full-screen without exporting?

    I wonder if I can manage my polished videos in FCP 7's projects and watch them in full screen mode just as I have done in Aperture 3 without having to export them first.