Statement or preparedStatement

Hi all guys,
Please tell me when we use Statement and when preparedStatement?
As many times we use preparedStatement so what is the use of Statement ?
And what is the advantage of using preparedStatement ? What is difference between in both ?
please reply !!!!!!!!!
amitindia
India

I was hoping you would ask that ;-)
Suppose your web application asks the user for their ID number. They type it into a box and click submit. This ends up calling the following method:
public List processUserID(String idNumber)
   throws SQLException
   String query = "SELECT role FROM roles WHERE id = '" + idNumber + "'";
   ResultSet rs = this.connection.executeQuery(query);
   // ... process results ...
}If out of a sense of informed malice, your user enters the following text into the ID number field:
12345'; TRUNCATE role; SELECT 'They may be able to drop the contents of your role table, because the string that ends up in "query" will be:
SELECT role FROM roles WHERE id = '12345'; TRUNCATE role; SELECT ''They have successfully injected SQL into your application that wasn't there before, hence the name. The specifics of this depend to some extent on your database, but there's some pretty portable SQL you can use to achieve this.
On the other hand, if you use a prepared statement:
public List processUserID(String idNumber)
   throws SQLException
   String query = "SELECT role FROM roles WHERE id = ?";
   PreparedStatement statement = this.connection.prepare(query);
   statement.setString(id,idNumber);
   ResultSet rs = this.connection.executeQuery(query);
   // ... process results ...
}The database is told to compile the SQL in query first. The parameter is then submitted - so whatever you put into it will never get executed as SQL (well, ok, it's possible if you're passing it as a parameter to a stored proc, but it's very unlikely) - it will just return no matching records (because there won't be any users with id "12345'; TRUNCATE role; SELECT '"
Hope that clarifies.
Dave.

Similar Messages

  • 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

  • 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!

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

  • 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!

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

  • 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;

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

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

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

  • Creating and closing statements

    Hi
    I am new 2 JDBC and have a few doubts,
    I need 2 move forward and backwards in the resultset, i am using the following declaration for that
    stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
    can i use the same declaration for the resultsets where i only need 2 move forward?
    also i use different functions for running different queries, should i create n close statements seperately in each function, or should i create statement once n for all wen im loading the driver and use that in all da functions?
    thanks a ton!

    You can use it but before using it for second time. you have to make it null.No. No. No. Setting it to null does nothing particularly good for you. it makes the object eligible for garbage collection, which is going to happen anyway as soon as the Statement is reused.
    You need to call close() before reusing a Statement (or PreparedStatement).
    If your code has any chance of ever being used in a multi-threaded environment (such as a web service), then you should use local Statement objects. There are also a lot of good design reasons for making them local, but for a single-threaded application, you certainly could use a single global Statement.

  • A question about PreparedStatement and ORA-03115 error

    Dear all,
    I have an issue with JDBC and I would appreciate if you could kindly give me a hand.
    I'm using:
    - Oracle Database 11g Enterprise (Release 11.1.0.6.0)
    - JDBC thin driver version: ( 11.1.0.7.0-Production)
    - JDK 1.6
    - Operating system: Linux (Ubuntu 8.10)
    Here is my code
    import java.sql.*;
    public class Main
        public static void main(String[] args)
            String dbURL = "jdbc:oracle:thin:@localhost:1521:mydatabase";
            String username = "scott";
            String user_password = "tiger";
            try
                Connection connection = DriverManager.getConnection(dbURL, username, user_password);
                String query_text = "SELECT * FROM mytable";
                Statement statement = connection.createStatement();
                ResultSet query_result = statement.executeQuery(query_text);
                connection.close();
            catch (SQLException e)
                for (Throwable t: e)
                    t.printStackTrace();
    }This works pretty well without any problem. But when I want to use PreparedStatement instead of Statement I receive the ORA-03115 error message, that is, when I replace the Statement with PreparedStatement in the following way:
    String query_text =
            "SELECT first_name, ?, id, ?, job_title, salary  FROM mytable "+
            "WHERE id IN ('id14', ?, 'id17', 'id18')";
    PreparedStatement prepared_statement =  connection.preparedStatement(query_text);
    prepared_statement.setString(1, "last_name");
    prepared_statement.setString(2, "birthday");
    prepared_statement.setString(3, "id02");
    ResultSet query_result = prepared_statement.executeQuery(query_text);I get the following:
    java.sql.SQLException: ORA-03115: unsupported network datatype or representation
         at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70)
         at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:133)
         at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:206)
         at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:455)
         at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:413)
         at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:1034)
         at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:194)
         at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:791)
         at oracle.jdbc.driver.T4CPreparedStatement.executeMaybeDescribe(T4CPreparedStatement.java:866)
         at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1186)
         at oracle.jdbc.driver.OracleStatement.executeQuery(OracleStatement.java:1377)
         at oracle.jdbc.driver.OracleStatementWrapper.executeQuery(OracleStatementWrapper.java:387)
         at mysqlpackage.Main.main(Main.java:33)Therefore, right after
    ResultSet query_result = prepared_statement.executeQuery(query_text);the exception is thrown,
    why it works with Statement but not with PreparedStatement? I tested with several other queries, insert a new row, delete a row, everytime it works well, but when I want to use PreparedStatement instead of Statement, again I have this error message.
    Any idea?
    Thanks in advance,

    OK, I found myself the answer.
    First error, I had use ? also for column names, which is not accepted as the SQL query has to be precompiled.
    Second error: Instead of writing
    ResultSet query_result =  prepared_statement.executeQuery(query_text);I had to write:
    ResultSet query_result =  prepared_statement.executeQuery();I tested with the following
    String query_text =
                  "SELECT first_name, last_name, id, birthday, job_title, salary "+
                  "FROM myenterprise "+
                  "WHERE id IN (?, ?, ?, ?) ";
                PreparedStatement prepared_statement =
                        connection.prepareStatement(query_text);
                prepared_statement.setString(1, "id02");
                prepared_statement.setString(2, "id04");
                prepared_statement.setString(3, "id08");
                prepared_statement.setString(4, "id09");
                ResultSet query_result =  prepared_statement.executeQuery();And it works pretty well now! :)

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

Maybe you are looking for