Commit on each iteration

I have a problem here with transactions and I'm not to sure how to handle this with Java/JDBC.
I have a loop like this:
[begin transaction] setAutoCommit(false);
[select some rows from table a joined with b]
while( there are stil rows ) {
[update table a]
[update table c]
[end transaction] commit(); setAutoCommit(true);
but in this way I lock for myself table "a" for the whole loop and that prevents me from running other instances of the same query which would access other rows in the same table... and worse, if something goes wrong I loose all the processing done so far.
what I want is something like this:
[select some rows from table a joined with b]
while( there are stil rows ) {
[begin transaction] setAutoCommit(false);
[update table a]
[update table c]
[end transaction] commit(); setAutoCommit(true);
but how can I achieve this? Would I have to call connection.createStatement() in each iteration? Would I have to use two separate connections, one for the main loop and one for the updates? I can't figure it out.
Thanks in advance.
Christian.

You can reuse a statement if you don't need previous resultsets obtained from this statement (in case of an instert, update or delete there is no resultset, so your statement can be reused as soon as you executed it).
Fo example you can execute:
Statement stmt = conn.createStatement();
for (int idx = 1; i <= 10; i++) {
    stmt.executeUpdate(
        "UPDATE A SET VALUE = VALUE + 10 WHERE ID = "+idx);
    stmt.executeUpdate(
        "UPDATE B SET VALUE = VALUE - 10 WHERE ID = "+idx);
}but if you will execute the same statements, only changing some values, I recommend you to use PreparedStatements, 'cause they are much faster, for example:
PreparedStatement stmt1 = conn.prepareStatement(
    "UPDATE A SET VALUE = VALUE + 10 WHERE ID = ?");
PreparedStatement stmt2 = conn.prepareStatement(
    "UPDATE B SET VALUE = VALUE + 10 WHERE ID = ?");
for (int idx = 1; i <= 10; i++) {
    stmt1.setInt(1, idx);
    stmt1.executeUpdate();
    stmt2.setInt(1, idx);
    stmt2.executeUpdate();
}both blocks of code do the same thing, but the second is faster. In the first case, the server have to compile 20 sql statements and execute the same number, but in the second case the server only compile 2 sql statements and executes 20. So the second is a lot faster.
rivas.

Similar Messages

  • Query update on each iteration problem (MS SQL Sever / ODBC / Native Driver

    Hello,
    I�ve been working to learn some Java and now JDBC over the past 10 or so months.
    I think I have a general understanding of how to perform queries and work with data using JDBC. However, I�ve run into a problem. I�m trying to do a query of a set of data in a database based on the value of a status column. I want to loop over the messages and perform various functions with the data then update their status in the database. It�s preferable to do these 250 to 1000 rows at a time, but no more and no less.
    I�m connecting to MS SQL Server 2000, currently with ODBC. I�ve also tried it with the Java SQL Server 2000 drivers provided by Microsoft with the same results.
    I�ve found that I can do a one table query and loop though it with a while (rs.next()) {�} and run an Update statement with executeUpdate on each iteration without any problems, no matter the number of rows returned in query.
    I have not been able to use the updateString and updateRow inside the while loop. I keep getting errors like this at the line with the updateRow():
    Exception in thread "main" java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC]Row update failed.
    This occurs no mater how many rows I select, 1 or more.
    The real problem I�ve been having is that the query I need to loop though joins across several tables and returns some rows from some of those tables. This only seems to work when I query for 38 or less selected rows and I use an Update statement with executeUpdate on each iteration. The updateString and updateRow methods never work. Any number of rows selected greater than 38 causes a deadlock where the Update is waiting for the select to compete on the server and the Update can�t proceed until the Select is complete.
    As I stated above I�ve tried both ODBC and the native SQL Server driver with the same results. I have not tried any other databases, but that�s moot as my data is already in MS SQL.
    Questions:
    How can I avoid or get around this 38 row limit without selecting each row, one at a time?
    What am I doing wrong with the updateString and updateRow?
    Is there a better approach that anyone can suggest?
    Here�s some sample code with the problem:
    import java.sql.*;
    public class db1{
         public static void main(String[] args) throws Exception{
              Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
              String url = "jdbc:odbc:eBrochure_live";
              Connection con = DriverManager.getConnection(url, "sa", "d3v3l0p");
              Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
              Connection con = DriverManager.getConnection("jdbc:microsoft:sqlserver://dcm613u2\\dcm613u2_dev:1433", "sa", "d3v3l0p");
              Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
              Statement stmt2 = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
              stmt.executeUpdate("USE [myDatabase]");
              stmt2.executeUpdate("USE [myDatabase]");
              String qGetMessages = "SELECT TOP 250 t1.messageUUID, t1.subjectHeader, t2.emailAddress as toAddress " +
              "FROM APP_Messages as t1 JOIN APP_addressBook_contacts as t2 " +
              "     On t1.toContactID = t2.contactID " +
              "WHERE t1.statusID = 'queued'";
              ResultSet rs = stmt.executeQuery(qGetMessages);
              while (rs.next()) {
                   String messageUUID = rs.getString("messageUUID");
                   String subjectHeader = rs.getString("subjectHeader");
                   System.out.println(messageUUID + " " + subjectHeader);
                   String updateString = "UPDATE APP_Messages " +
                        "SET statusID = 'sent' " +
                        "WHERE messageUUID = '" + messageUUID + "' ";
                   stmt2.executeUpdate(updateString);
              con.close();
    Thanks for the help,
    Doug Hughes

    // sorry, ps.close() should be outside of if condition
    String sql = "UPDATE APP_Messages SET statusID = 'sent' WHERE messageUUID = ?";
    Statement statement = con.createStatement();
    PreparedStatement ps = con.prepareStatement(sql);
    ResultSet rs = statement.executeQuery("your select SQL");
    if ( rs.next() )
    ps.clearParameters();
    ps.setString(1, rs.getString("your column name"));
    ps.executeUpdate();
    ps.close();
    rs.close();
    statement.close();

  • Write one line of numbers to a text-file or write multiple lines each iteration?

    Hi,
    I'm currently working on an application that has a few different while-loops running at the same time. One loop acquires the data (DAQloop), another shows the data (raw and processed data) on graphs (Graphsloop) and yet another stores the data in an open ascii text file (Storageloop).
    The data is passed on from the DAQloop to the Storageloop through a queue. At this moment I let the Storageloop take up the first element of the queue (the oldest) to store it in the textfile each iteration. I was wondering however whether it would be better to let the Storageloop take up all the elements currently available in the queue to store it in one go.
    Does anybody have any ideas on this? Which would be better performancewise? The textfile is already opened and is just passed on as a refnum.
    Thx!
    Giovanni Vleminckx
    Using LabVIEW 8.5 on Windows7
    Solved!
    Go to Solution.

    With the normal LabVIEW file primitives, you will get your best disk speed when you write about 65,000 bytes to disk at once (or read, for that matter).  When I write similar code, I include a string buffer in the write loop.  Every time I get write data, I add it to the string.  When the string hits 65,000 bytes, I write to disk.  You could break this into three loops, as well - a read, buffer, and write.  Depending upon you current chunk size, you could see over an order of magnitude change in disk write speed.  This write operation is often throttled by the conversion from binary to ASCII, not the disk I/O.  If you do this, be careful with your buffer.  You can get some serious slowdowns depending upon how you implement it.  This post has some details and examples.
    This account is no longer active. Contact ShadesOfGray for current posts and information.

  • Start and stop a loop automatica​lly subtractin​g at each iteration

    Hi there,
    I know that there are some topics about it, but I could not find any solution, especially because I use the version 7.1 and cannot open new version files.
    My problem is as follows:
    I need to charge a tank from 6 to 10 in the morning, every day during 3 days. The process must start and stop automatically, which means, no bottoms to start or stop. The start and stop conditions come from the hour.
    I start with a big loop of 72 iterations, which corresponds to 72 hours.
    The tank must start at level 6 every time it starts.
    After the start, 1 unit must be subtracted in each iteration. Which means, that at 6 am the tank has level 10, at 7 am level 9 and so on. In the end, at 10 am the tank level is equal to 2.
    In the next day, the process must start again and the tank must start at level 6.
    Any suggestions? Thanks in advance.
    Solved!
    Go to Solution.

    While this may work it can be improved significantly. This really isn't a state machine. This is basically the same as your flat sequence with the exception of using a While loop with a Case statement to implement each frame.
    You should define what your actions are and create a typedefed ENUM naming them. State names of 1 through 24 are meaningless. Not to mention in your code many of the cases are duplicates of others. That would mean that all of those can be one state with logic to determine what action/state comes next. A properly defined state machine would not need the outside For loop. Without knowing your specific needs some examples of reason state names would be the following: Start, Stop, Exit, Error, Initialize, Get Tank Level, Fill Tank, Drain Tank, Idle, etc. Can you see how these are easier to understand than 1 through 24.
    There are lots of examples of state machines here. Try a search and take a look at some of them.
    Mark Yedinak
    "Does anyone know where the love of God goes when the waves turn the minutes to hours?"
    Wreck of the Edmund Fitzgerald - Gordon Lightfoot

  • Need new result file for each iteration of a loop

    I am using TestStand 2010 SP1.  I have a main sequence that essentially does the following:
    Initialize the test equipment and set up the test environment [Sequence Call]
    Start Loop
    Run Tests [Sequence Call]
    End Loop
    Because testing can continue for hours, the resultant report file is enormous and difficult to evaluate. I need to create a new result file for each loop iteration.  I know that starting a new execution of “Run Tests” will create a result file for each iteration of the loop, but the new execution will not have access to the handles to the test equipment that were made during initialization.  The testing is time critical, therefore initializing the test equipment and setting up the test environment must occur outside of the loop. 
    How can I programmatically create a new result file at the beginning of the loop and close the result file at the end of the loop?  I am open to any other suggestions.  Thank you in advance for your help!

    Hi,
    You could modify your process model by making a copy of Test UUTs entry point. Then make the loop that usually tests multiple UUTs into your loop. Take the loop and init out of your sequence. You can init in PreUUTLoop or the other pre loop sequence, and maybe store your references in runstate.root.Locals and pass them to MainSequence. Then you can use Report Options to set it for separate report files.
    cc

  • Writing bytes to serial port in each iteration of loop

    Hello everyone,
                      Well I am new to labview, my question might of beginner's level but i have searched the forums and didnt find content regarding it. Kindly help me through it as i am really stuck in it for last three days. 
                      I have to make a packet of bytes in each iteration depending upon the bytes i get from array which is input to for loop. Taking five bytes and then making packet according to protocol. Once packet is made i have to send it to serial port in the same iteration. So for each iteration i have to send packet to serial port. I have tried the shift registers, local variables, and also the autoindexing which returns the array at the end of loop. But these things dont solve my problem. Kindly help me solvng this issue.
    Many many thanks in advance
    Engr. Yasir Amin 

    First of all thanks alot for your reply.
                             The problem is that i have made separate subVI for this protocol stuffing and the output of that subVI is attatched to the serial visa write in another main  VI in which i am using this VI. I have sent parameters to subVI which makes the packet and then send the output, the output is then sent to visa serial write. Actually that visa serial write is common to many subVIs, On the interface its user's choice to select the request he wants to send. The based on the request the particular subVI is chosen and then that subVI generates the string which is in main VI. which is written to serial port. All other subVis are working fine becoz they dont have loop they simply make the string and send it to port. But this subVi with the loop has the problem as it sends only the last iteration string to port.
    I cant post the code as i am using my laptop in my room and the code is in office laptop But tomorrow i can share it from office
    Thanks
    Yasir

  • Appended text file in loop adds unwanted delimiter value at end of each iteration.

    I am using 'Export To Spreadsheet.vi' in a loop which saves a text file and appends data from a 1D array waveform for each iteration. My problem is that at the end of every iteration an extra delimiter value is appended to the file. When I then attempt to graph my data, I get gaps, as seen below (circled in black).
    When I start to analyze the data, I'm sure this will be a nuisance. I can not seem to find a solution to this problem. Any advise would be greatly appreciated. 
    Thanks.
    Solved!
    Go to Solution.

    Export Waveforms... does indeed place an end of line at the end of the last line, resulting in a gap when the next batch of data is appended.  I just had the same problem with a VI that a co-worker had written.
    The fix is non-trivial. First, make a copy of the Vi to a new location and with a modified name. (If you change a VI in vi.lib, it causes all kinds of problems.)
    Then go in and place string indicators various places until you find where the extra EOL characters are. The output of Array to Spreadsheet String ends with EOL.  I do not have all the other changes readily accessible.  I think we also changed the time format because the default setting lost resolution.
    That VI opens, writes, and closes the file on every call so this is not very efficient for frequent calls.
    It would almost be easier to write a Waveform to String formatting VI which does what you want and then use the standard OpenCreate/Replace File, Write to Text File, and Close File functions.
    Lynn

  • How to insert elements into an array after each iteration of a for loop

    I am new to labview and working on an application where I am supposed to store an element into an array (without overwriting) after each iteration in a for loop. I have tried using Build Array Function keeping the indicator outside the for loop and played with indexing but didn't work. Please suggest me an idea how to do it.
    Thanks
    Solved!
    Go to Solution.

    Thank you for your suggestion.Here is my actual application attached . In the first image, a difference in time is evaluated and an enum const of insert into array is passed to the shift register where it takes to Insert element into array phase (Second image). I need to enter the time difference into an array after every loop iteration. Please have a look and could you let me know where I am mislead.
    Attachments:
    Image 1.JPG ‏88 KB
    Image 2.JPG ‏71 KB

  • How create a variable that changes (by 0.05) on each iteration in a loop?

    We are trying to control  New Era Syringe pumps using Labview. We want that those pumps could dispense different volumes on wells. For example 0.05ml in well one (using actuators we can move the wells),  0.1ml in well 2, 0.15ml in well 3 and so on. We think that we may need a "For loop" in which the number of iteration is the number of wells, but we do not know how to create a variable, inside the loop that can increase .05 on each iteration, and then we can use that variable as a "volume input" in our program.

    Hi tbob,
    multiple add operations with floats may induce more errors than a multiply/divide due to floating point representations (especially on numbers that can't be represented exactly, like 0.05)... The next step in this routine might be a comparison of setpoint and measurement value
    Message Edited by GerdW on 05-10-2010 08:04 PM
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome

  • Displaying data in chart for each iteration of FOR loop

    Hi Flex experts,
    I'm coding an Actionscript routine that has a series of
    complex calculations within a for loop. I would like to display
    some of the calculation results in a Flex chart at the end of each
    iteration of the loop. Thus far, I can only get the chart to
    display the results from the last iteration, but not any of the
    preceding iterations.
    Any tips or pointers would be greatly appreciated.
    Thanks,
    Dean

    Please have look at callLater method. You can call your
    chart-updating method thru callLater and that might help.
    Otherwise, can you share some of your code in the loop?
    ATTA

  • Writing a different set of finite samples at each iteration

    Hello,
    I have a basic question regarding usage of the DAQmx VI's. How can I configure my code to write a different set of 1D DBL data to the write buffer at each iteration?
    Thanks,
    John
    Attachments:
    LIA.vi ‏52 KB

    Sorry, I just figured it out (placed a 'Stop' at the beginning of the task).
    John

  • Old operating systems allowed you to click on recipients when sending emails without adding a comma after each address. Now with the new and improved system, I have to stop and add a comma after each name. How can I avoid this?

    With the new OSX system, whenever I send an email with multiple recipients, I need to physically add a comma after each address. I never needed to do that with all the other older systems, it was done automatically. How can I fix this frustrating glitch?

    option discovered in preferences. Really this and any feature that moves deletes or edits a users data should as far as possible be OFF BY DEFAULT. It shouldn't by default and without the users specific say do this dangerous and unnecessary thing without even letting the user know what it's doing!!! And then cause me a few hours (as i'm new to mac) searching for the option so as to switch it off. If i hadn't noticed the status cage declaring that it was copying files then i might never have twigged that this insane thing was occurring. And if i hadn't of noticed i would have been left maintaining the contents of the folder i copied the files to, the folder which as far as i was informed and so believed was also the location of the music files i was playing. How does Apple justify this 'genius' piece of software non-design? Surely it will hurt no one if this was off by default for new users - overall at least i dare say it would cause a lot less distress in the future for the unsuspecting public at large. Thanks for the support.

  • How to save a chart after each iteration in a for loop?

    Hello,
    I have written code which initializes a spectrometer. Once initialized, if the "Capture" button is pushed, the spectrometer takes a new spectrum three times (see for loop) every second. This spectrum is displayed as a chart in my front panel. My code runs fine...it will update the spectrum every second.
    However, I want to be able to save each of these three iterations as separate graphs. Basically, I want to click "Capture" and have my code save three charts to a specified folder. How do I go about doing this?
    I've attached my VI.
    Thanks.
    Solved!
    Go to Solution.
    Attachments:
    Spectrometer Iteration.vi ‏444 KB

    Use Build Array to make a 2D Array of your X and Y data and use Write To Spreadsheet File to save the data.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines

  • Loop through the collection of elements and give 15 elements in each iteration.

    For example I have 100 pnr numers and i need 15 set of pnrs each time i iterate through the 100 pnrs using XQUERY.
    I have to hit a service to get PNR details , I have 100 PNR's but I can hit only with 15 at a time

    Hello,
    Did the issue resolved? Just as Visakh16 post above, it is hard to interpret without the sample data. Please post more details for further analysis.
    You can refer to the following article about FLWOR Statement and Iteration in XQuery:
    http://technet.microsoft.com/en-us/library/ms190945.aspx
    Regards,
    Fanny Liu
    Fanny Liu
    TechNet Community Support

  • Database commit on each instance created

    Hi
    I am new to BPEL, and I have a requirement as follows:
    1. Read a csv/text file through file adapter
    2. For each row from the file, using the DB adapter, insert data into a tableA.
    3. Select the data inserted in step2, and depending on the value, do an update/insert on tableB.
    BPEL is creating 1 instance in the console for step1 to step3, and I need to commit each instance.
    Seems like BPEL is doing a commit at the end of all the rows read from the file, rather than for each line read from the csv file.
    Could someone please help me on this, I would greatly appreciate your help.
    Thanks in Advance,
    Shashi.

    Found the answer on this MetaLing document: 460293.1. We did it and it works like a champ. Since the servers are all firewalled inside and only 2 DBAs have access to the package and trigger we have no security exposure in the wallet password.

Maybe you are looking for

  • Need a generic data type to hold any string

    Hi,   I m trying to write a program which can log data from any table into a Trace Z table. I have used FIELD-SYMBOLS: <line>. to get the line of that table. But now I want to dynamically know what are the field names of this line structure and the d

  • Bridge question

    I just upgraded to Creative Cloud.  I have been using PS6 and Bridge.  I used to be able to click on the image, in Bridge, and it would open in Photoshop.  This is not happening in Bridge CC.  What can I do to make this work in CC?

  • How to embed the webcontent in Email

    Hi Everyone, would you kindly let me know how to embed the webcontent in emails. Thank you.

  • HT5787 My MacBook Pro will not let me log on. How do I fix this? Can apple reset it?

    My MacBook Pro will not let me log on. How do I fix this? Can apple reset it?

  • BW Query Usuage Statistics

    Hi Experts, I have a requiremnet to analyse Query Usuage in our nvironment. I basically need below infomation a. How many times a query was accessed b. Number user Attempts per day. c. Query runtime d. Query used by which user e. Query last accessed