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