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;

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

  • Issue with stat() and symbolic links

    Has anyone experienced the following issue with stat() ?
    #include <stdio.h>
    #include <string.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <unistd.h>
    int main( int argc, char **argv )
    struct stat buf;
    if( argc < 2 )
    return 0;
    char *link = strdup( argv[1] );
    if( stat( link, &buf ) == -1 ) {
    puts( "Error" );
    return 1;
    if( ( S_IFLNK & buf.st_mode ) == S_IFLNK )
    puts( "Is link" );
    else
    puts( "Not link" );
    return 0;
    If you compile and run the above code (or similar code), you would expect it to report that the given argument is a symbolic link when indeed the argument is a symbolic link; though, instead of the expected happening, the following happens as shown below:
    $ gcc -o islink islink.c
    $ ln -s /tmp link
    $ ./islink link
    Not link
    $
    Is anyone else experiencing this? My filesystem is ext4. The same error happens when using the S_ISLNK() macro.

    man 3p lstat
    DESCRIPTION
           The lstat() function shall be equivalent to stat(),  except  when  path
           refers  to  a symbolic link. In that case lstat() shall return informa‐
           tion about the link, while stat() shall return  information  about  the
           file the link references.

  • 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

  • Problems with setDate and PreparedStatement

    Hi,
    Having a bit of a problem with the code showed below. Im getting an SQLException that roughly translated says: "Non-implemented additional function". Im using an MS SQL Server Database.
              String sql = "Update the_table SET column1= ? AND SET column2= ? WHERE something='" + a_variable+"';";
              PreparedStatement updateODate = connection.prepareStatement(sql);
              updateODate.setDate(1, oDate);         //oDate and sbDate are java.sql.Date's
              updateODate.setDate(2, sbDate);
              updateODate.executeUpdate();Is there something wrong with my SQL-statement? Perhaps my SQL skills aren't the best...
    Regards
    -Karl XII

    You could get jTDS ( http://jtds.sourceforge.net ) or the trial version of a commercial driver (I would recommend the first). To use a different driver, just add the driver's jar file to your classpath and use that driver's Driver implementation and URL format instead.
    You can find the relevant information for each driver on its home page. For jTDS you would use:
            Class.forName("net.sourceforge.jtds.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:jtds:sqlserver://server/db", "sa", "");Alin.

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

  • Best Practice with States and lots of code lines

    Hi.
    This is my first application in flex.
    I'm ok with as3.
    Now, in as3 we were 'forced' to work mostly with external classes so hardly we have a unique code page with lots of lines.
    In flex, using States leads to build codes with lots of line IF we think on states as web site pages.
    I'm not sure it I understand it right. You mean: if an user visits a website built with 10 pages, but the users access only 2 pages, all that 8 remaining pages would have to be download to the swf the user loads?  (this is, considering the usage os states as pages)
    I'm building a system where the user logs to use it.
    2 states at now:  login page and home page.
    I access the db, and get the user and password with this event dispatched from the db.result (this works, however i found it too-old-style looping. Is there a better way, of course, which?)
    protected function usersService_resultHandler(event:ResultEvent):void
                    allUsers = event.result as ArrayCollection;
                    for (var i:uint;i<allUsers.length;i++){
                        if(allUsers[i].user == tx_user.text && allUsers[i].password == tx_password.text)
                            currentState = "home";
                        else
                            Alert.show("Fault", "Login");
    While I have start to build the "home" page/state, I realized that my code would dramatcally increase. Is it the best practice? Do I have to call another url after login (to open a Session - please, some Session tutorials in flex)? Or I keep doing all in states? I'm afraid my swf would grow bigger.
    Thanks

    Ok.
    The problem is that I'm not used to PHP, and I have generated the code to deal with the server automatically via Flex.
    However I could add a new function, and I could guess how to catch values in the db to compare.
    its a frankenstein function, but i'm afraid it also works. By now, there is no way to know whether user mistyped password or username.
    public function getUserVerification($user, $pass) {
            $stmt = mysqli_prepare($this->connection, "SELECT user, password FROM $this->tablename where user=? AND password=?");
            $this->throwExceptionOnError();
            mysqli_stmt_bind_param($stmt, 'ss', $user, $pass);       
            $this->throwExceptionOnError();
            mysqli_stmt_execute($stmt);
            $this->throwExceptionOnError();
            mysqli_stmt_bind_result($stmt, $row->user, $row->password);
            if(mysqli_stmt_fetch($stmt)) {
              return 1;
            } else {
              return 0;
    Also I had to update the _Super_UsersService.as  Class flex had generated before when I first created a php code to deal with db.
    Finaly, I had to assign return and input types for the new function I've created.
    Amazing... it works.
    Now, when pressing the submit button on the login, flex sends user and password so php compare them instead looping it in a Array.
    Also, I have made all this code inside a "loginView" component. So my main app is clean again.
    I guess I understand the idea of using components and reusing them as many as possible. I just have to get used to how to access a component value from outside and vice-versa.
    Now, the creationPolicy is something I would look for. This might be interesting.
    Thanks a lot.
    Btp~

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

  • Statement and Prepared Statement

    if i write a same query with statement and preparedStatement
    like
    Select * from emp_detail where emp_id =20;
    stmt= con.createStatment();
    rs = stmt.executeQuery(query);
    and using preparedStatement
    Select * from emp_detail where emp_id =?;
    pstmt= con.prepareStatement();
    pstmt.setInt(1,20);
    rs = stmt.executeQuery(query);
    Using which statment(Statement or Prepared Statement) the data will retrive fast and why.... in these case ????

    Statement should be quicker than Prepared Statement, because
    Statment do only one thing: send that sql to server or run that sql directly.
    Prepared Statement should do two (or more than two)things:
    1. parse your sql first, prepare a store procedure, then call that store procedure.
    Or
    2. prase your sql first, then use your value to replace "?" for getting a new sql, then work like Statement.
    Prepared Statement is quiker when you use it repeatedly.

  • Firefox was my default, it went to boxes with statements,now it will not load,

    Firefox stopped working yesterday for no reason, when I open the default page, all I get is 9 oblong boxes stacked one on top of the other with statements and a search button for each one, but nothing happens, which means I cannot access my computer via firefox.

    Thanks for the input, but it still didn't work. I tried resetting, then I reinstalled the Photobucket App. It asked me to sign in, but when I attempt to go to "My Albums" at the bottom of the page, it just freezes when it says "Loading Albums". Just like it did before.
    At least the camera still works. I'm about ready to take a picture of a target, set it up about 50 feet away and use this **** thing for the one thing it's good for, catching a bullet.
    What really ****** me off was when I wanted to speak to a live Apple employee for help. $19 for help fixing what is obviously a problem with their "update"?!?! I'm totally convinced that Apple could care less about their customers. Sure, some people are not experiencing problems with iOS6, but from the posts here searching for help, it's clear Apple totally dropped the ball on this one.
    Thanks Apple.

  • Customer Statement with opening and closing balances

    Dear Forum,
    The users want to generate the Customer Statement with opening and closing balances like the traditional one. The statement now generated gives the list of all open items as on date, but the users want the statement with opening balances as on the date of the begining of the range specified and the closing balance at the end of the period for which the statement is generated. Is there a way to generate the same from the system.
    Thanks for the help.
    Regards,

    Hi,
    SPRO> Financial Accounting (New) > Accounts Receivable and Accounts Payable > Customer Accounts > Line Items > Correspondence > Make and Check Settings for Correspondence
    You can use the program RFKORD10 with correspondance type SAP06 for your company code
    This program prints account statements and open items lists for customers and vendors in letter form. For account statements, all postings between two key dates, as well as the opening and closing balance, are listed.
    Regards,
    Gaurav

  • FI Customer Account Statement with Debit and Credit Columns

    Hi SAP Expert,
    We are using form (developed from T-code: SE71) to send customer account statment for only open items this is working fine.
    Now My wants customer account statement for all transactions but with debit and credit in a separate columns. is there any way we fulfill these kind of request?
    if any particular logic then let me know please.
    thanks in advance
    b/r
    prashant rane

    Dear Vivek,
    You logic is helpful can I apply this in SE71 form development?
    Below is my customer layout format
    Document # | Document Date | Reference | Debit Amt | Credit Amt |
    In bottom toal Debit / credit balance figure
    can I use any code/login is SE71 form or I will need to create any development report which involves user exit?
    I am looking for SE71 optios first
    thanks in advance
    Prashant Rane

  • Specific problem with buttons and states

    Hello,
    I first apologize for using Google Translate :-(
    I have a problem with InDesign not solve. It is for a digital publication.
    My goal is:
    A 'gallery' button is pressed and the ball image appears with three buttons: "Previous image", "Next image" and "close gallery".
    I do not want the gallery to be visible, or buttons that control, until the button is pressed "gallery", so I think all buttons except "gallery" with the "hidden until activated" option selected.
    I want the gallery, and buttons that control it, disappears when I press the button "close gallery".
    What I call "Gallery" is an image that fills the screen.
    After placing the image on your site have become the property button "Hidden until activated."
    Then convert this button in order to several states (what I will call "button states") and by the successive states with the images I want to show in the gallery.
    I think the interactions of the buttons.
    When button "gallery" I assign the following "I click the"
    - "Go to state"
    - Hide "gallery"
    - Show "close gallery"
    - Show "previous picture"
    - Show "next image"
    - Show "button states."
    The buttons "Previous Image" and "Next Image" are assigned, respectively, to go to previous state and go to the next state.
    When button "close gallery" I assign the following "I click the"
    - Show "gallery"
    - Hide "close gallery"
    - Hide "previous picture"
    - Hide "next image"
    - Show "button states."
    The buttons "Previous Image" and "Next Image" are assigned, respectively, to go to previous state and go to the next state.
    When button "close gallery" I assign the following "I click the"
    - Show "gallery"
    - Hide "close gallery"
    - Hide "previous picture"
    - Hide "next image"
    - Hide "button states."
    I put it up and working properly until I press "close gallery". Then I hide the buttons "close gallery", "previous image" and "next picture" but it keeps me visible "button states" showing the last image that was shown.
    Do not know how to fix this and I'm going crazy!
    Please can anyone help me?
    The solution may be another approach but without using "Folio Overlays".
    Thank you very much.

    I've moved your post to the DPS forum.
    I'm afraid the way you're doing this is not going to work with DPS.
    This should all be done with a multi state object. The first state would contain nothing but a button to go to the first state. After that set up each state with the proper buttons. Without seeing the file it's a bit difficult for me to envision exactly what you want to do.

  • Financial statements to comply with IFRS and US GAAP.

    Hi everyone,
    We need to start reporting our external financial statements to comply with IFRS and US GAAP.
    There are some primary differences in the 2 accounting principles relates to PPE (Fixed Assets/Capital Expenditure) and therefore multiple/different valuations of the assets, they need to be provided for.
    Do you know how we can comply with both the IFRS and US GAAP reporting requirements in general using the tools in SAP ?
    Thanks in advance and best regards.
    Dago

    Hi,
    A few tips: Asset Area 1 should be mapped to IFRS and linked to leading ledger. Area 20 is mapped to GAAP and liked to non-leading ledger. Area 1 should be 100% depreciated to capital expenditure in the very first depreciation run, which will allow you to report capital expenditure at the end of the month. Area 20 is for depreciation over the life (the regular GAAP stuff).
    Regards,
    Ming
    Edited by: Minghong Ji on Jun 15, 2011 6:48 PM

Maybe you are looking for