JDBC:事务

2019-04-12  本文已影响0人  KaveeDJ

使用事物

练习:删除前十条数据

public class TestJDBC {

    public static void main(String[] args) {

        // 加载数据库驱动
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        try (
                Connection c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8", "root", "admin");
                Statement st4Query = c.createStatement();
                Statement st4Delete = c.createStatement();
                Scanner s = new Scanner(System.in);
            ) 
            {
            // 先把自动提交关闭
            c.setAutoCommit(false);
            // 查出前十条
            ResultSet rs = st4Query.executeQuery("select id from Hero order by id asc limit 0,10 ");
            while (rs.next()) {
                int id = rs.getInt(1);
                System.out.println("试图删除id=" +id+" 的数据");
                st4Delete.execute("delete from Hero where id = " +id);
            }
            
            // 是否删除这10条
            while (true) {
                System.out.println("是否要删除数据(Y/N)");
                
                String str = s.next();
                if ("Y".equals(str)) {
                    c.commit();
                    System.out.println("提交数据");
                    break;
                } else if ("N".equals(str)){
                    System.out.println("放弃数据");
                    break;
                }
            }
            
            }
            catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读