Properties文件的讀取。

db.properties

jdbc.driver=oracle.jdbc.OracleDriver
jdbc.url=jdbc:oracle:thin:@localhost:ORCL
jdbc.user=root
jdbc.password=


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class DBUtility {
    private static Properties properties =new Properties() ;
    private static String driver = null;
    private static String url = null;
    private static String user = null;
    private static String pwd = null;
    static {
        try {
            // 加載配置文件
            properties.load(DBUtility.class.getClassLoader().getResourceAsStream(
                    "day01/v3/db.properties"));
            driver = properties.getProperty("jdbc.driver");
            url = properties.getProperty("jdbc.url");
            user = properties.getProperty("jdbc.user");
            pwd = properties.getProperty("jdbc.password");
            Class.forName(driver);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    public static Connection openConnection() throws SQLException {
        return DriverManager.getConnection(url, user, pwd);
    }
    public static void closeConnection(Connection con) {
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                System.out.println("關閉連接時發生異常");
            }
        }
    }
}

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