views:

35

answers:

1

I have table in DB,e.g. TableOne.
By some rules i should commit N records from this table to other tables.
Is it possible to do with jdbc or ResultSet or CachedRowSet?

Preliminary flow, as i see:
1. loop through ResultSet of TableOne
2. increment counter if certain condition is met
3. if condition is not met, it's time to commit to other DB tables N records=counter
4. commit these N records

So,the question is in step 4.
How it may be implemented?

Thank you.

A: 

The purpose of the counter is unclear, so I am going to assume that you are just using it to illustrate the fact that you are only committing records that match the condition.

Try constructing an insert statement that does all the work:

INSERT INTO table2 (a, b, c)
    SELECT a, b, c FROM table1
WHERE myConditionIsMet

The other option is to loop over the record set and insert a record every time the condition is met. You should wrap the loop in a transaction so nothing gets committed until after the loop has completed. My JDBC is a little rusty so here is a psuedocode example:

connection.startTransaction()
for row in records
    if row condition
        connection.execute('INSERT ROW STATEMENENT')
connection.commitTransaction()

The first approach is preferable, but there maybe some situations where the condition can't be determined within an SQL expression.

mikerobi
thank you for answer.what do you mean "to wrap in transaction"?
sergionni
@sergionni, If you don't understand what I mean by "wrap in a transaction", you should read up on database theory. I have added an example that shows what you would do, the why is a bit outside the scope of your original question. In this case, I did it for performance reasons, but it also has big implications for error handling.
mikerobi