题目:
当c.setAutoCommit(false);时,事务是不会提交的,只有执行使用 c.commit(); 才会提交进行。
设计一个代码,删除表中前10条数据,但是删除前会在控制台弹出一个提示:
是否要删除数据(Y/N)
如果用户输入Y,则删除
如果输入N则不删除。
如果输入的既不是Y也不是N,则重复提示
代码如下:
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
List<Integer> list = new ArrayList<>();
Scanner sc = new Scanner(System.in);
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
String sql1 = "SELECT * FROM tb_emp limit 0, 10";
pstmt = conn.prepareStatement(sql1);
rs = pstmt.executeQuery();
while (rs.next()) {
int id = rs.getInt(1);
list.add(id);
System.out.println("试图删除数据" + id + "行");
}
while (true) {
conn.setAutoCommit(false);
for (int i = 0; i < list.size(); i++) {
String sql2 = "delete from tb_emp where id = ?";
pstmt = conn.prepareStatement(sql2);
pstmt.setInt(1, list.get(i));
pstmt.execute();
}
System.out.println("是否要删除这10条数据(Y/N)?");
String str = sc.nextLine();
if (str.equalsIgnoreCase("Y")) {
conn.commit();
System.out.println("已删除10条数据");
break;
}
else if (str.equalsIgnoreCase("N")) {
System.out.println("未删除数据");
break;
}
else {
System.out.println("输入错误");
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}