面试题答案
一键面试import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class TransactionExample {
private static final String URL = "jdbc:mysql://localhost:3306/yourdatabase";
private static final String USER = "yourusername";
private static final String PASSWORD = "yourpassword";
public static void main(String[] args) {
Connection connection = null;
PreparedStatement statement1 = null;
PreparedStatement statement2 = null;
try {
// 1. 建立数据库连接
connection = DriverManager.getConnection(URL, USER, PASSWORD);
// 2. 开启事务
connection.setAutoCommit(false);
// 第一个更新操作
String sql1 = "UPDATE your_table SET column1 =? WHERE id =?";
statement1 = connection.prepareStatement(sql1);
statement1.setString(1, "value1");
statement1.setInt(2, 1);
statement1.executeUpdate();
// 模拟可能抛出异常的操作
if (Math.random() < 0.5) {
throw new SQLException("模拟异常");
}
// 第二个更新操作
String sql2 = "UPDATE your_table SET column2 =? WHERE id =?";
statement2 = connection.prepareStatement(sql2);
statement2.setString(1, "value2");
statement2.setInt(2, 2);
statement2.executeUpdate();
// 3. 如果所有操作都成功,提交事务
connection.commit();
System.out.println("事务提交成功");
} catch (SQLException e) {
// 4. 如果有异常,回滚事务
if (connection != null) {
try {
connection.rollback();
System.out.println("事务回滚");
} catch (SQLException ex) {
System.err.println("回滚事务时出错: " + ex.getMessage());
}
}
// 5. 处理异常信息以便调试和维护
System.err.println("数据库操作异常: " + e.getMessage());
e.printStackTrace();
} finally {
// 6. 关闭资源
if (statement2 != null) {
try {
statement2.close();
} catch (SQLException e) {
System.err.println("关闭statement2出错: " + e.getMessage());
}
}
if (statement1 != null) {
try {
statement1.close();
} catch (SQLException e) {
System.err.println("关闭statement1出错: " + e.getMessage());
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
System.err.println("关闭连接出错: " + e.getMessage());
}
}
}
}
}
上述代码通过JDBC
实现了一个事务操作,具体说明如下:
- 开启事务:通过
connection.setAutoCommit(false)
关闭自动提交,开启事务。 - 执行数据库操作:执行多个
UPDATE
语句进行数据库更新。 - 提交事务:如果所有操作都成功,调用
connection.commit()
提交事务。 - 回滚事务:如果任何一个操作抛出
SQLException
,在catch
块中调用connection.rollback()
回滚事务。 - 异常处理:捕获异常后,打印异常信息以便调试和维护。
- 关闭资源:在
finally
块中关闭PreparedStatement
和Connection
,确保资源正确释放。