jdbcを使用してデータベースに接続し、トランザクション処理を行う方法は何ですか?
JDBC(Java Database Connectivity)は、Javaプログラミング言語でデータベースに接続するためのAPIです。以下はデータベースに接続してトランザクション処理を行う例コードです。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class TransactionExample {
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
try {
// 1. 加载数据库驱动
Class.forName(“com.mysql.cj.jdbc.Driver”);
// 2. 建立数据库连接
String url = “jdbc:mysql://localhost:3306/database_name”;
String username = “username”;
String password = “password”;
connection = DriverManager.getConnection(url, username, password);
// 3. 开启事务
connection.setAutoCommit(false);
// 4. 执行SQL语句
statement = connection.createStatement();
String sql1 = “INSERT INTO table_name (column1, column2) VALUES (‘value1’, ‘value2’)”;
String sql2 = “DELETE FROM table_name WHERE id = 1”;
statement.executeUpdate(sql1);
statement.executeUpdate(sql2);
// 5. 提交事务
connection.commit();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
// 6. 回滚事务
try {
if (connection != null) {
connection.rollback();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
} finally {
// 7. 关闭数据库连接
try {
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
} }
コードの中で、まずデータベースドライバをロードし、DriverManager.getConnection()メソッドを使用してデータベースとの接続を確立します。setAutoCommit(false)メソッドを使用して自動コミットを無効にします。SQL文の実行後にcommit()メソッドを使用してトランザクションをコミットし、例外が発生した場合はrollback()メソッドを使用してトランザクションをロールバックします。最後に、close()メソッドを使用してデータベース接続を閉じます。実際の状況に応じて、例示コード中のデータベース接続URL、ユーザー名、パスワード、SQL文、テーブル名などを変更してください。