Skip to Content
author's profile photo Former Member
Former Member

Commit / RollBack

Hi,

I want to execute 2 or more database operation in one transcation with commit/rollback mechanism.

Below is my code,

How can i make it has commit /rollback (in one transaction).

Thanks.

InitialContext ctx = new InitialContext();

DataSource ds = (DataSource) ctx.lookup("jdbc/SAPXXXDB");

Connection con1 = ds.getConnection();

Connection con2 = ds.getConnection();

PreparedStatement pstm1 =con1.prepareStatement("insert into ZTABLE1(...)Values(...)";

PreparedStatement pstm2 =con2.prepareStatement("insert into ZTABLE2(...)Values(...)";

pstm1.executeUpdate();

pstm2.executeUpdate();

con1.close();

con2.close();

Add a comment
10|10000 characters needed characters exceeded

Assigned Tags

Related questions

1 Answer

  • Best Answer
    author's profile photo Former Member
    Former Member
    Posted on Sep 09, 2009 at 06:04 AM

    Hi Cemil Bozlagan ,

    When a connection is created, it is in auto-commit mode. This means that each individual SQL statement is treated as a transaction and is automatically committed right after it is executed.

    The way to allow two or more statements to be grouped into a transaction is to disable auto-commit mode by using Connection object.

    con.setAutoCommit(false);

    Once auto-commit mode is disabled, no query statements are committed until you call the method commit explicitly. All statements executed after the previous call to the method commit are included in the current transaction and committed together as a unit.

    Have a look

    PreparedStatement pstm1 =con1.prepareStatement("insert into ZTABLE1(...)Values(...)";

    PreparedStatement pstm2 =con2.prepareStatement("insert into ZTABLE2(...)Values(...)";

    pstm1.executeUpdate();
    pstm2.executeUpdate();
    con.commit();
    con.setAutoCommit(true);

    To roll back the transaction based on ur requirement u can use

    con.rollback()

    Regards,

    srikanth

    Add a comment
    10|10000 characters needed characters exceeded

Before answering

You should only submit an answer when you are proposing a solution to the poster's problem. If you want the poster to clarify the question or provide more information, please leave a comment instead, requesting additional details. When answering, please include specifics, such as step-by-step instructions, context for the solution, and links to useful resources. Also, please make sure that you answer complies with our Rules of Engagement.
You must be Logged in to submit an answer.

Up to 10 attachments (including images) can be used with a maximum of 1.0 MB each and 10.5 MB total.