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