Using a database transaction with JDBC : Transaction « Database SQL JDBC « Java






Using a database transaction with JDBC

 

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class Main {
  public static void main(String[] args) throws Exception {
    Connection connection = null;
    try {
      Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

      connection = DriverManager.getConnection("jdbc:sqlserver://MYSERVER;databaseName=MYDATABASE",
          "USERID", "PASSWORD");

      connection.setAutoCommit(false);

      Statement statement = connection.createStatement();

      statement.executeUpdate("UPDATE Table1 SET Value = 1 WHERE Name = 'foo'");
      statement.executeUpdate("UPDATE Table2 SET Value = 2 WHERE Name = 'bar'");

      connection.commit();

    } catch (SQLException ex) {
      connection.rollback();
    }

  }
}

   
  








Related examples in the same category

1.Demo MySql Transaction
2.Test Supports Transactions
3.Transaction Pairs
4.Transaction Info
5.JDBC Transaction
6.Transaction Pairs 2