简述JDBC(二)

本人小白一枚,欢迎大家一起讨论学习,如有错误,还望大家指教。

通过上一篇的学习,我们发现在操作数据库时会有很多重复的代码,为了解决这个问题,我们将要写一个工具类来简化代码。

public class JDBCUtils {
    
    private static String url;
    private static String username;
    private static String password;
    
    static {
        try {
            // 用Properties来配置数据库的用户名和密码
            Properties properties = new Properties();
            // 可以使用类加载器ClassLoader来获取src路径下的jdbc.properties文件
            ClassLoader loader = JDBCUtils.class.getClassLoader();
            URL resource = loader.getResource("jdbc.properties");
            properties.load(new FileReader(resource.getPath()));
            // 获取配置文件中的值
            url = properties.getProperty("url");
            username =  properties.getProperty("username");
            password = properties.getProperty("password");
            // 注册驱动
            Class.forName(properties.getProperty("driver"));
        } catch (Exception e) {
            e.getStackTrace();
        }
    }

    /**
     * 获取数据库连接对象
     * @return 
     */
    public static Connection getConnection() {
        try {
            return DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 释放资源
     * @param statement 执行sql对象
     * @param connection 数据库连接对象
     */
    public static void closeResources(Statement statement, Connection connection) {
        if (statement != null) {
            try {
                statement.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (connection != null) {
            try {
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 释放资源
     * @param resultSet 结果集对象
     * @param statement 执行sql对象
     * @param connection 数据库连接对象
     */
    public static void closeResources(ResultSet resultSet, Statement statement, Connection connection) {
        if(resultSet != null) {
            try {
                resultSet.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        closeResources(statement, connection);
    }
}

练习
例子:登录案例,用户通过键盘录入用户名和密码来进行登录操作,我们会使用上面的工具类。
在这里插入图片描述

public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入用户名:");
        String username = scanner.nextLine();
        System.out.println("请输入密码:");
        String password = scanner.nextLine();
        if (login(username, password)) {
            System.out.println("登录成功!");
        } else {
            System.out.println("用户名或密码失败!");
        }
    }

    public static boolean login(String username, String password) {
        if (username == null || password == null) {
            return false;
        }
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            connection = JDBCUtils.getConnection();
            String sql = "SELECT * FROM user model WHERE model.username = ? AND model.password = ?";
            statement =  connection.prepareStatement(sql);
            statement.setString(1, username);
            statement.setString(2, password);
            resultSet = statement.executeQuery();
            return resultSet.next();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
             // 释放资源
            JDBCUtils.closeResources(resultSet, statement, connection);
        }
        return false;
    }

成功

请输入用户名:
admin
请输入密码:
123456
登录成功!

失败

请输入用户名:
123
请输入密码:
123
用户名或密码失败!

简述:一个包含多个步骤的业务操作。如果这个业务操作被事务管理,则这多个步骤要么同时成功,要么同时失败。
事务四个特性 ACID:原子性、一致性、隔离性、持久性
操作:

  1. 开启事务
  2. 提交事务
  3. 回滚事务

使用Connection对象来管理事务

  • 开启事务:setAutoCommit(boolean autoCommit) :调用该方法设置参数为false,即开启事务
    • 在执行sql之前开启事务
  • 提交事务:commit()
    • 当所有sql都执行完提交事务
  • 回滚事务:rollback()
    • 在catch中回滚事务

在上面的user表中增加一个工资(salary字段),类型为int,并且添加数据
在这里插入图片描述
我们模拟张三为李四进行转账500业务,即张三工资变为500,李四变为1500。

public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = JDBCUtils.getConnection();
            // 开启事务
            connection.setAutoCommit(false);
            String sql = "UPDATE user set salary = ? WHERE username = ?";
            statement = connection.prepareStatement(sql);
            statement.setInt(1, 500);
            statement.setString(2, "张三");
            statement.executeUpdate();
            // 手动抛出异常
            int i = 1 / 0;
            statement.setInt(1, 1500);
            statement.setString(2, "李四");
            statement.executeUpdate();
            System.out.println("转账成功");
            // 提交事务
            connection.commit();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("转账失败");
            // 回滚事务
            try {
                if (connection != null) {
                    connection.rollback();
                }
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        } finally {
            // 关闭资源
            JDBCUtils.closeResources(statement, connection);
        }
    }

打印结果

转账失败
java.lang.ArithmeticException: / by zero
at affair.Demo.main(Demo.java:23)

我们手动抛出异常之后,再次查询,发现张三与李四的工资都没有发生改变,如果我们不使用事务,如果在转账期间发生异常,会发生张三转账钱被扣除,而李四的账户却没有增加,由此而知,事务的存在时多么的重要!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值