import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseUtil {
private static final String URL = "jdbc:jtds:sqlserver://localhost:1433/db_name";
private static final String USERNAME = "username";
private static final String PASSWORD = "password";
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(URL, USERNAME, PASSWORD);
}
}
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class TransactionExample {
public static void main(String[] args) {
Connection connection = null;
try {
connection = DatabaseUtil.getConnection();
connection.setAutoCommit(false);
String sql1 = "INSERT INTO table1 (column1, column2) VALUES (?, ?)";
PreparedStatement statement1 = connection.prepareStatement(sql1);
statement1.setString(1, "value1");
statement1.setString(2, "value2");
statement1.executeUpdate();
String sql2 = "UPDATE table2 SET column1 = ? WHERE column2 = ?";
PreparedStatement statement2 = connection.prepareStatement(sql2);
statement2.setString(1, "value3");
statement2.setString(2, "value4");
statement2.executeUpdate();
connection.commit();
} catch (SQLException e) {
if (connection != null) {
try {
connection.rollback();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
} finally {
if (connection != null) {
try {
connection.setAutoCommit(true);
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);