DB

//static:只要类存在,成员标量就存在
    private static String driver;
    private static String url;
    private static String user;
    private static String userPassword;

    //静态语句块加载类的同时会执行这段代码
    static {
        //找到对应的属性文件:db.properties
        InputStream is = BaseDao.class.getClassLoader().getResourceAsStream("db.properties");
        Properties props = new Properties();
        try {

            props.load(is);
            //读取属性文件中各个key对应的值,复制给相对的成员变量
            //成员变量名 = props.getProperty("driver");(属性文件的key值)
            driver = props.getProperty("driver");
            url = props.getProperty("url");
            user = props.getProperty("user");
            userPassword = props.getProperty("userPassword");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //完成JDBC的第一步与第二步操作
    public static Connection getConnection(){
        Connection con = null;

        // 1.加载并注册驱动
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        try {
            con = DriverManager.getConnection(url,user,userPassword);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return con;
    }
    //返回值connection
    //完成JDBC的第678步
    //查询操作时,关闭打开的对象
    public static  void close(ResultSet rs, PreparedStatement pstmt, Connection con){
        try {
            if (rs != null) rs.close();
            //7.
            if (pstmt != null) pstmt.close();
            //8.
            if (con != null && !con.isClosed() ) con.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    //增删改操作时,关闭打开的对象
    public static  void close(PreparedStatement pstmt, Connection con){
        //直接调用三个参数的关闭方法
        close(null, pstmt, con);
    }

  

posted @ 2020-12-15 12:36  卿家尘归尘  阅读(478)  评论(0编辑  收藏  举报