用DBUtils封裝jdbc

db.properties放在src目錄下

public class DBUtil {
    private static Properties prop = new Properties();

    static {
        try {
            prop.load(DBUtil.class.getClassLoader().getResourceAsStream("db.properties"));
            //加載數據庫驅動(可以省略)
            Class.forName(prop.getProperty("driverClassName"));
        } catch (Exception e) {
            System.out.println("加載db.properties配置文件信息異常....");
            e.printStackTrace();
        }
    }

    public static Connection getConnection() {
        Connection conn = null;
        try {
            String url = prop.getProperty("url");
            String username = prop.getProperty("username");
            String password = prop.getProperty("password");
            conn = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            System.out.println("獲取數據庫連接異常...");
            e.printStackTrace();
        }
        return conn;
    }

    public static void close(Connection conn, Statement st) {
        if (st != null) {
            try {
                st.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(Connection conn, PreparedStatement st, ResultSet rs) {
        if (st != null) {
            try {
                st.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章