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);
    }
相關文章
相關標籤/搜索