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語句和表名等信息。