What is a better approach, batch or prepared statement?

Hi,
In my application, the user account property will be retrieved from DB and the last login time will be updated after a successful sign on. There are two query statements in this procedure; select and update. What is a better approach in JDBC to deal with the two queries: batch or prepared statement?
Thanks.

Hi, Duffy,
Thanks for your input.
I would like to use PreparedStatement with batch update. From my reading, however, it is not suitable to use PreparedStatement with batch update. At less, I haven't see a single example on the tutorial or article sections of this site. I am not sure the following is valid or not:
               stmt = connection.prepareStatement(INSERT_SMT_QUERY_STR);
               stmt.setLong(1, details.getRegardID());
               stmt.setLong(2, details.getWriterID());
               stmt.setInt(3, details.getVisibility());
               stmt.setString(4, details.getSubject().trim());
               stmt.setString(5, details.getContent().trim());
stmt.addBatch() <-- what goes into here?

Similar Messages

  • What's the better approach?

    Hi, I was just making a program that access a DB through JDBC, and I got myself into this dilemma
    What's the better approach to make a connection to a DB?
    approach #1(use of singleton pattern)
    import java.sql.*;
    public class DBConnection {
        private ResultSet rs;
        private Connection conn;
        private PreparedStatement ps;
        private static boolean singleton = false;
        private DBConnection() throws Exception{
            Class.forName("driverPath").newInstance();
         conn = DriverManager.getConnection("url", "user", "pass");
         singleton = true;
        public static DBConnection getInstance() throws Exception{
            if(singleton)
             return null;
            return new DBConnection();
        protected void finalize() throws Throwable {
            //close the connection and release resources...
            singleton = false;
        //Methods to make DB querys and stuff.     
    }approach #2 (make a connection only when doing querys)
    public class DBConnection {
        private ResultSet rs;
        private Connection conn;
        private PreparedStatement ps;
        public DBConnection() throws Exception {
            Class.forName("driverPath").newInstance();
        //Just some random method to access the DB
        public ArrayList<Row> selectAllFromTable() {
            ArrayList<Row> returnValue = new ArrayList<Row>();
         try {
             conn = DriverManager.getConnection("url", "user", "pass");
             //make querys and fill the arraylist with rows from the table
         } catch(Exception ex) {
             returnValue = null;
             ex.printStackTrace();
         } finally {
             if(ps != null)
                 ps.close();
                if(rs != null)
              rs.close();
             if(conn != null)
              conn.close();
         return returnValue;
    }I know this classes maybe don't even compile and I don't handle the Exceptions, I'm just trying to make a point about how to manage the connection
    So, what it's the better approach in your opinions? #1? #2? neither?

    Hi,
    I'm resurrecting this thread to ask is this approach OK?
    I'm trying to make a single MySql JDBC connection accessible throughout the model.
    I'm planning to use it in a Swing application. Whilst I realise the Swing apps are inherently multi-threaded, everything I plan to do can (I think) be done within the constraint that all access to model happens on the EDT, and the user will just have to wear any unresponsiveness.
    package datatable.utils;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    abstract public class MySqlConnection {
         public static final String URL = "jdbc:mysql://localhost/test";
         public static final String USERNAME = "keith";//case sensitive
         private static final String PASSWORD = "chewie00";//case sensitive
         private static final Connection theConnection;
         static {
              String driverClassName = "com.mysql.jdbc.Driver";
              try {
                   Class.forName(driverClassName);
                   theConnection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
              } catch (Exception e) {
                   throw new DAOException("Failed to register JDBC driver class \""+driverClassName+"\"", e);
         public static Connection get() {
              return(theConnection);
    }Is there a better solution short of c3po? Which I played with, but couldn't work out how to configure.
    Thanx guys (and uj),
    keith.

  • What is the better approach to populate Ref cursor into ADF business Component

    HI All,
    I have a requirement where I get the search results by joining more than 10 tables for my search criteria.
    What is the best approach to populate into ADF BCs.
    I have to go with Stored Procedure approach where I input the search Criteria and get the cursor back from the same.
    If I populate VO programmatically then the filtering at column level is a challenge.
    Anyone Please help me. Thanks in Advance.
    Thanks,
    Balaji Mucheli.

    The number of tables to be joined for a VO's query shouldn't matter - if the query is valid and fixed.
    Are you saying that you have logic to decide which tables to join to create the correct query?  I admit that would be a difficult thing to do, other than with a programmatic VO.  However, there are two possible solutions for doing this without a programmatic VO.
    Instead of your procedure returning a REF CURSOR, you can create an object type (CREATE TYPE) and a nested table of that type.  Then you have a function that returns an instance of the nested table.  The query in the VO is SELECT my_column... FROM TABLE(CAST my_table_function(:bind_variable) AS my_table_type).  You may have trouble getting the VO to accept this query as valid SQL, but it IS valid and it DOES work.
    Create a VO to be the master VO - it should have all the attributes that you intend to use, but the query can be anything, even a SELECT from DUAL.  Then create other VOs that subclass the master VO - one for each major variation of the query.  When you use the VO, use the data control for the master VO to create your pages, but change the pageDef to make the VO name a variable (with expression language).  Then you can set that variable to the correct child VO for the query that needs to execute.

  • Simulating a mutiple line text entry-what is the better approach?

    I brand new to Captivate but hail from a past Authorware background. I'm creating an exercise where the user must add 5 individual terms to a list.
    I'd like to accomplish this with one text box but it looks like I am going to have to have 5 separate slides and swap things such that on entry 2 I show entry 1 and on entry 3 I show entry 1,2 etc.
    Also-I need to switch the text in the entry box. I'm going to reserach the manual on this as I am sure I am missing something.
    Thanks

    You will need 5 Text Entry Boxes, but not necessarily on 5 slides. It is possible to time each TEB on the timeline.  Let the user give the first item in a first TEB on the start of the Timeline. The standard action when confirming the entry (by a button or a shortcut like Enter) is 'Continue', so the slide will continue and get to the second TEB. The user gives the second entry, after confirming the slide will continue, you are getting to the third TEB.
    I hope this is not too confusing. Perhaps this screenshot will explain more:

  • What is it better ?

    Hi All,
    I would like to know your option...
    What is the better approach between (a) and (b) ?
    a)
    MyClass t = null;
    for (int i;......) {
        t = new MyClass();
    }b)
    for (int i;......) {
        MyClass t = new MyClass();
    }Cheers,
    ste

    What about memory usage or garbage collector ?
    hardly a difference, if any.
    In my opinion B (or c) is better from the garbage
    collector point of view, not sure about memory
    usage.it isn't. At most, and only if we're talking about a method that runs beyond the next garbage collection cycle, a single instance might take one garbage collection cycle longer to become eligable for garbage collection and be collected in the first scenario.
    Unless you're talking about objects taking massive amounts of memory per instance that's peanuts.
    Of course, the most expensive operation is new
    MyClass(), but in B the jvm should create any time a
    new variable (i mean a new pointer container); in A
    just the same pointer changes value (pointing to the
    new object)
    If you're so worried about those few theoretical microseconds you might save why not declare every variable as a member of the class so you won't have to declare them every time you pass through that method?
    Not saying you should (good design practice says you shouldn't) but given your reasoning that would be the logical choice.
    But you can't say what'll happen exactly. The compiler or JVM might well decide to optimise away that declaration.

  • Count of Rows Updated with prepared statement batch

    I am using a batch of prepared statements for update operation. (pstmt.executeBatch())
    Configuration I am using
    WLS 6.1sp2 Connection pool - Oracle Thin driver - TX Datasource
    DB - Oracle 8.1.7
    The batch update works well i.e data gets updated and committed. BUT I am not
    getting back the count of number of rows updated.
    Is there any thing more required on WLS side ?
    Thanks in Advance

    The Oracle drivers do not return the updated row counts from batched updates.
    Try running the attached program with the thin driver
    java Batch oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@host:port:database user password
    You will see that returns -2, which indicates that the number of rows updated is unknown.
    This does meet the JDBC spec.
    "Harshad Nanal" <[email protected]> wrote in message news:3f8a455f$[email protected]..
    >
    I am using a batch of prepared statements for update operation. (pstmt.executeBatch())
    Configuration I am using
    WLS 6.1sp2 Connection pool - Oracle Thin driver - TX Datasource
    DB - Oracle 8.1.7
    The batch update works well i.e data gets updated and committed. BUT I am not
    getting back the count of number of rows updated.
    Is there any thing more required on WLS side ?
    Thanks in Advance[Batch.java]

  • When to use prepared statement in java?

    Hi all,
    If we have query like select * from {tablename} (Here tablename is the variable) then will the use of prepared staement improve the performance? My guess is use of statement in this case is a better option rather than prepared statement as the tablename may change for every other query.I think are not useful if tablename changes.They are useful only when the where clause has dynamic values.

    cantor wrote:
    Are you sure that your approach is possible? The next example causes exception for me.
    PreparedStatement ps = conn.prepareStatement("select * from ?");
    ps.setString(1, "TABLE_NAME");
    ps.executeQuery();
    I didn't say that he should solve it in that way. He should create one prepared statement like this "select a, b, c from tablename1" and another prepared statement when he wants to execute "select d, e, f from tablename2"
    >
    And as I understand, this code will not improve perfomance (and even will not work). As I said it can.
    Prepared statements make possible usage compiled queries inside DB. When DB gets prepared statement call, it need to parse it only once. And it can collect some statistic to improve execution plan. But when table name is not specified, this approach will not work.Yes it might. There are database drivers that can cache prepared statements and it's isn't likely that he executes that query on more than e.g. 20 tables?
    The database can also cache compiled statements in a cache.
    Kaj

  • Best Practice: Combine prepared statements with ;

    Hi,
    I would like to know what the best prctice is for combining prepared statements to give the query below
    INSERT INTO my_table (value) VALUES (?); SELECT LAST_INSERT_ID()The reason for this is that i have written a simple DB wrapper to handle my database connections and queries based on a property file containing sql strings. I would prefer not to change this wrapper code, but be able to specify combined queries in the sql string if possible.
    Thanks in advance

    Have you thought about using Batch statements ?

  • Advantages of using prepared statement..... ?

    can anyone please tell me that what r the advantages of using prepared statements.
    for eg in case if statement object is executed inside a for loop where query is executed multiple times the sql query is compiled outside loop and therefore compilation is done only once. which makes sense
    But if there the query is not executed multiple times then what is the real benifit of using prepared statement . because the statement object will be closed after executing the query.
    and a new statement object will be created when other user access the same code.
    please clearify my doubts
    thanks
    Pankaj

    Other advantages of using PreparedStatement:
    1. It's easier to create SQL that looks like "Select This, That, TheOther from Something where ID=? and Usage=?" than to try to generate that with string concatenations.
    2. You don't have to deal with escaping quote characters that happen to appear in strings you want to insert in your database.
    3. PreparedStatements can do some things that Statement can't, such as updating very large text columns.

  • Using once created prepared statement with different connections in Oracle

    Can I use same statement cash using different connections in Oracle
    For example I have a prepared statement p1. After its using i close connection (return it to the pool)
    Next time I want use p1 statement using another connection.
    Question : When I creat p1 in second time ,is it returned from cash or created as a new statement. And what I should do to use once prepared statement using differend connections.
    Thaks.

    As far as I know a PreparedStatement lives and dies with the Connection that created it. So, you cannot use a PreparedStatement with other Connection instances than the one that created it.
    You will have to recreate the PreparedStatement for each time you open a connection, or use the same PreparedStatement and NOT close the Connection in between. The last suggestion can be risky though, if you never close the connection...
    Jakob Jenkov
    www.jenkov.com

  • Prepared Statement - Using IN()

    Does anybody have a good solution to using an IN clause in a preapred Statement?
    The query I have might be "Select * from dual where 1 IN(1,2,3,4);"
    OR
    "Select * from dual where 1 IN(1,2,3,4, 5, 6, 7);"
    OR
    "Select * from dual where 1 IN(n number of arguments);"
    So I don't know how to parameterize this to take advantage of prepared statements.
    Does anybody have any solutions?

    So if you can't use IN with prepared statements, then is it better not to use prepared statements so we don't blow through the prepared statement cache?

  • What would be the better approach at showing a course is complete?

    (OT: I'm being evlauated to do some online software simulations using Captivate so I'm trying to merge my Authorware "thinking" with Captivate)
    I have a 14 slide simulation; task to edit preference files. Scoring is not necessary but getting to slide 14 is all that is necessary.
    Presently I have a click object on slide 13 whose reporting options is "Include in Quiz" with adding 1 point.
    So I have a course with Objective ID=Quiz10111 Interaction ID=Interaction11184 and a score of 1.
    But I also note in the reporting preferences I could use "Slide views only." So maybe this is all that is necessary?
    I'm not that savy (yet) with LMS's but if I wanted to write this data out as a tab delimited file on the hosting server what should I consider? Authorware had a function "WriteExtFIle." Would a button on the last slide set to execute Javascript be a better approach?
    Another idea looking for a point of view. If I get the project I am considering a 2 month contract Adobe Acrobat Connect Pro to get more confortable with this approach. Would this help?
    FYI...I just downloaded the Captivate 4 manual. Last modified on May 19th according to the doscument.
    Thanks

    Regarding your function hanging, that seems to be because your loop never ends. Also the inner query is missing a WHERE clause:
    Select Translate(comnt_rec.comment_text,'%#$^',' ') into repvalue from test_comnt;  <-- How many rows will this bring back?However I don't think you meant to query the test_comnt table at all - it looks as though you just wanted to assign the result of the TRANSLATE expression (btw please, TRANSLATE() or translate() but not Translate() - the parser doesn't care but it drives me nuts), in which case just
    repvalue := translate(comnt_rec.comment_text,'%#$^',' ');or even include the expression in the cursor itself and save yourself the trouble.
    Another thing that drives me nuts, although not the rest of the world apparently, is the name "c1" for a cursor. Why don't you name your variables "v1", "v2" etc? If you had two cursors would you seriously name the second one "c2"?
    While I'm at it, what kind of a name is "test_comnt"?

  • What is the best approach to delete multiple list items

    Hi
    I want to delete multiple list items at once, what is best approach please suggest?
    Ramesh

    Hi Ramesh,
    Better approach for removing many items from a list is to use the ProcessBatchData method provided by the SPWeb class. First, you need a collection of the list items
    you want to remove, and then you can use the Get-SPListItem function to retrieve a list of items that match a given criteria. Then build a batch string with resultant items and call the ProcessBatchData method.
    Here is the sample code.
    function Get-SPList($webUrl, $lstUrl)
    $webObj = Get-SPWeb -identity $webUrl
    $lstObj = $webObj.GetList($lstUrl);
    return $lstObj
    $spList = Get-SPList -webUrl "http://mysitecollecton/MySite" -lstUrl "http://mysitecollecton/MySite/Lists/EmpInfo"
    $spQuery = new-object Microsoft.SharePoint.SPQuery
    $camlQuery =
    "<Where>
    <Eq>
    <FieldRef Name='Department' />
    <Value Type='Text'>HR</Value>
    </Eq>
    </Where>"
    $spQuery.Query = $camlQuery
    $spQuery.RowLimit = 100
    $spListItemCollection = $spList.GetItems($spQuery)
    # Create batch remove CAML query
    $batchRemove = '<?xml version="1.0" encoding="UTF-8"?><Batch>';
    # The command is used for each list item retrieved
    $command = '<Method><SetList Scope="Request">' +
    $spList.ID +'</SetList><SetVar Name="ID">{0}</SetVar>' +
    '<SetVar Name="Cmd">Delete</SetVar></Method>';
    foreach ($item in $spListItemCollection)
    $batchRemove += $command -f $item.Id;
    $batchRemove += "</Batch>";
    # Remove the list items using the batch command
    $spList.ParentWeb.ProcessBatchData($batchRemove) | Out-Null
    Please don't forget to mark it answered, if your problem resolved or helpful.

  • What are the different approaches to do Fault Handling?

    What are the different approaches to do Fault Handling?

    for uplodig data to non sap we have 2 methodes
    i) if u know bapi u will use lasm
    2) bdc
    but u mentioned so many records isthere
    best thing is u will uplode all record sto al11 using XI interface
    then u have to write bdc / lsmw  program
    beter to go for lsmw before that u will find bapi
    if u will unable to find bapi
    u have to create bapi and use it in lasmw
    ofter that u have schedule the lsmw program as a bockground
    then u have to create a job for it
    and release from sm 37
    then u have to moniter through bd87
    if u want to go through i will help u.
    if it is usefull to u pls give points
    Saimedha

  • What is the best approach to store "dynamic" user accessibility ?

    Hi all,
    We are implemennting security in our ADF BC + Faces application. There is always requirement to hide/disable functionalities that a user is not allowed / authorized to access.
    Usually we do this during development time, based on what role the user is in. Using this approach, there is no way to change that , or give access to new role during runtime (after the deployment). This is what I call "static accessibility".
    In our apps, we need the give / revoke access to some functionalities during runtime. This is what I call "dynamic accessibility".
    One approach that comes to my mind is :
    We define the accessibility to each function that we want to protect (hide/unhide) in database tables. Then every time a use enter a page, read these tables through JDBC calls then store tha data in Managed Bean.
    Has anybody here implement this "dynamic accessibility" ?
    Is there a better approach ?
    Thank you very much,
    xtanto

    Saeed,
    SRDemo uses a managed bean that checks is user in role when called and returns true or false. Another approach - more elegant - is the use of a security property resolver as available
    http://jsf-security.sourceforge.net
    Regarding dynamic permissions, the use of JAAS seems to be a good solution. ADF Security uses JAAS permissions to assign component access to users.
    E.g. if the user role manager has access to edit the salary column, then the security constraint added to the update button could be
    #{!bindings.<attribute binding>.updateable}
    Note that ADF Security sets the updateable flag on an attribute.
    Or you use
    #{bindings.<iterator binding>.permissionInfo.create}
    #{bindings.<attribute binding>.permissionInfo.update}
    #{bindings.permissionInfo['pageDefName'].view}
    etc. to determine what a user can do or can't.
    Note that I haven't tested if the permissions are cached for a specific application or if they are checked each time again. If they are checked each time then this would be a performance penalty but allows to dynamically set permissions to user groups as obviously needed in your applications.
    No, we don't have tutorial for this. But a Oracle By Example for end-to-end security implementation is on my collateral plan for JDeveloper 11 (just need to write a doc writer ;-) )
    Frank

Maybe you are looking for

  • Problem with running exe in flex

    Hi I have made an flex application which reads dynamic xml data through RSS feed.I tested the swf in browser its working fine and data is updated on the application at regular intervals, then i created its exe through flash player 9 and tested. It ru

  • Selection-Block By default grey

    Hi, How to make the block in the selection-screen by default as greyed.

  • KM Document display on Portal

    Hi All, i uploaded a document under Content Administration->KM Content->root->documents->public documents->xyz.doc. what is to be done in order to display this document in an iView. what KM iView need to be used for this purpose. Regards, Kavitha

  • Passing Internal tables between pages (in stateless appl.)

    hi BSP gurus, how do I pass internal tables from one BSP page to another. The problem is that the appl. is stateless and hence I am not able to use the appl. class. thanks in advance, Ashish Walke

  • Would you help me to close my Adobe Creative Cloud account?

    Dear Sir/Madam, Hello! Would you help me to close my two of Adobe Creative Cloud account [personal information removed to foil spam bots... JTS] [This is an open forum, not Adobe support, please do not post personal information] My contact email [rem