Java学习笔记(六十四)—— JDBC(抽取工具类)

JDBC工具类
  • 概述:JDBCUtils,目的简化书写

  • 抽取JDBC工具类

    // 建立Properties配置文件
    url=jdbc:mysql:///db2
    user=root
    password=root
    driver=com.mysql.jdbc.Driver
    /*JDBC工具类提取*/
    public class JDBCUtils {
        private static String url;
        private static String user;
        private static String password;
        private static String driver;
        /*文件的读取只需要读取一次即可拿到数据,使用静态代码*/
        static {
            // 读取文件资源,获取值
            // 1.创建Properties集合对象
            Properties properties = new Properties();
            try {
                // 获取src路径下的文件的方式-->ClassLoader类加载器
                ClassLoader classLoader = JDBCUtils.class.getClassLoader();
                URL resource = classLoader.getResource("jdbc.properties");
                String path = resource.getPath(); // 获取觉得路径
                // 2.加载文件
                properties.load(new FileReader(path));
                // 3.获取数据,复制
                url=properties.getProperty("url");
                user=properties.getProperty("user");
                password=properties.getProperty("password");
                driver=properties.getProperty("driver");
                // 4.注册驱动
                Class.forName(driver);
            } catch (Exception e) {
                e.printStackTrace();
            }
    
        }
        /*获取连接对象*/
        public static Connection getConnection() throws SQLException {
            return DriverManager.getConnection(url,user,password);
        }
        /*释放资源方法*/
        public static void close(Statement stmt,Connection con){
            if(stmt!=null){
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(con!=null){
                try {
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        public static void close(ResultSet rs,Statement stmt, Connection con){
    
            if(rs!=null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(stmt!=null){
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(con!=null){
                try {
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    
    
    }
    	// 实现JDBC工具类
        public static void main(String[] args) {
            List<Account> all = findAll();
            System.out.println(all);
            System.out.println(all.get(0).getName());
        }
        public static List<Account> findAll(){
           /* 查询所有Account对象*/
            Connection con=null;
            Statement stmt =null;
            ArrayList<Account> accounts = new ArrayList<>();
            ResultSet rs=null;
            try {
                // 2.获取连接
                con = JDBCUtils.getConnection();
    
                // 3.定义sql语句
                String sql="select * from account";
                // 4.获取执行sql的对象
                stmt = con.createStatement();
                // 5.执行sql语句
                rs = stmt.executeQuery(sql);
                // 6.遍历结果集,封装对象,装载
    
                while (rs.next()){
                    int id=rs.getInt(1);
                    String name=rs.getString(2);
                    double money=rs.getDouble(3);
                    accounts.add(new Account(id,name,money));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                JDBCUtils.close(rs,stmt,con);
            }
            return accounts;
        }

练习

  1. 通过键盘录入用户名和密码,判断用户是否登录成功

    -- 1.创建数据表users
    CREATE TABLE users(
    	id INT PRIMARY KEY AUTO_INCREMENT,
    	username VARCHAR(30),
    	PASSWORD VARCHAR(30)
    )
    SELECT * FROM users;
    -- 数据表users添加数据
    INSERT INTO users(username,PASSWORD) VALUES('zhangsan','123'),('lisi','456');
    DROP TABLE users;
    // 2.创建登录的类
    public class JDBCDemo2 {
        /*登录方法*/
        public boolean login(String username,String password){
            if(username==null||password==null)
            return false;
            Connection connection=null;
            Statement statement=null;
            ResultSet resultSet=null;
            try {
                // 1.获取连接
                connection = JDBCUtils.getConnection();
                // 2.定义sql语句
                String sql="select * from users where username='"+username+"' and password= '"+password+"'";
                // 3.获取执行sql的对象
                statement = connection.createStatement();
                // 4.执行sql对象
                resultSet = statement.executeQuery(sql);
                // 5.判断
                    return resultSet.next();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                JDBCUtils.close(resultSet,statement,connection);
            }
    
            return true;
        }
    
        public static void main(String[] args) {
            // 1.键盘输入
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入用户名:");
            // 获取输入的用户名
            String username = scanner.nextLine();
            System.out.println("请输入密码:");
            // 获取输入的用户名密码
            String password=scanner.nextLine();
            // 2.调用方法,判断成功或者失败
           if(new JDBCDemo2().login(username,password)){
               System.out.println("登录成功");
           }else{
                System.out.println("登录失败");
           }
        }
    }
    	// 使用PreparedStatement对象防止sql的注入问题
    	    /*登录方法*/
        public boolean login(String username,String password){
            if(username==null||password==null)
            return false;
            Connection connection=null;
            PreparedStatement preparedStatement=null;
            ResultSet resultSet=null;
            try {
                // 1.获取连接
                connection = JDBCUtils.getConnection();
                // 2.定义sql语句
                String sql="select * from users where username=? and password=?";
                // 3.获取执行sql的对象
                preparedStatement = connection.prepareStatement(sql);
                // 4.给?赋值
                preparedStatement.setString(1,username);
                preparedStatement.setString(2,password);
                // 5.执行sql对象
                resultSet = preparedStatement.executeQuery();
                // 6.判断
                    return resultSet.next();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                JDBCUtils.close(resultSet,preparedStatement,connection);
            }
    
            return true;
        }
    
        public static void main(String[] args) {
            // 1.键盘输入
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入用户名:");
            // 获取输入的用户名
            String username = scanner.nextLine();
            System.out.println("请输入密码:");
            // 获取输入的用户名密码
            String password=scanner.nextLine();
            // 2.调用方法,判断成功或者失败
           if(new JDBCDemo3().login(username,password)){
               System.out.println("登录成功");
           }else{
                System.out.println("登录失败");
           }
        }
  2. 转账

     public static void main(String[] args) {
        Connection connection =null;
        PreparedStatement preparedStatementSub =null;
        PreparedStatement preparedStatementAdd =null;
        try {
            // 1.获取连接
            connection = JDBCUtils.getConnection();
            // 开启事务
            connection.setAutoCommit(false);
            // 2.定义sql
            String sqlSub="update account set money = money - ? where id=?";
            String sqlAdd="update account set money = money + ? where id=?";
            // 3.获取执行sql对象
            preparedStatementSub = connection.prepareStatement(sqlSub);
            preparedStatementAdd = connection.prepareStatement(sqlAdd);
            // 4.设置参数
            preparedStatementSub.setDouble(1,500);
            preparedStatementSub.setInt(2,1);
            preparedStatementAdd.setDouble(1,500);
            preparedStatementAdd.setDouble(2,2);
            // 5.执行sql
            preparedStatementSub.executeUpdate();
            int i=3/0;
            preparedStatementAdd.executeUpdate();
            // 提交事务
            connection.commit();
        } catch (Exception e) {
            // 回滚事务
            try {
                if(connection!=null)connection.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            JDBCUtils.close(preparedStatementSub,null);
            JDBCUtils.close(preparedStatementAdd,connection);
        }
    
    }
发布了113 篇原创文章 · 获赞 1 · 访问量 927

猜你喜欢

转载自blog.csdn.net/weixin_44876003/article/details/103432428