1. 程式人生 > >JDBC資料庫連線之配置檔案

JDBC資料庫連線之配置檔案

為了使程式碼靈活切易於擴充套件和維護,我們一般將資料庫配置資訊放入檔案中,比如:db.properties

url=jdbc:mysql://localhost:3306/day17
user=root
password=root
driverClass=com.mysql.jdbc.Driver
這時候使用類路徑讀取:
InputStream in = JdbcUtil.class.getResourceAsStream("/db.properties");
“/”表示classpath的根目錄(maven專案中放在resource目錄下即可,因為專案打包資原始檔放在class下)

程式碼如下:

public class JdbcUtil {
    private static String url = null;
    private static String user = null;
    private static String password = null;
    private static String driverClass = null;

    static{
        try {
        Properties prop = new Properties();
        InputStream in = JdbcUtil.class.getResourceAsStream("/bd.properties");
        prop.load(in);

        //讀取配置資訊
        url = prop.getProperty("url");
        user = prop.getProperty("user");
        password = prop.getProperty("password");
        driverClass = prop.getProperty("driverClass");

        //載入驅動
        Class.forName(driverClass);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("讀取配置檔案失敗");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.out.println("載入驅動失敗");
        }
    }

    /**
     * 連線
     */
    public static Connection getConnection(){
        try {
            Connection con = DriverManager.getConnection(url, user, password);
            return con;
        } catch(SQLException e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 查詢
     */
    public static void queryall(){
        try {

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查詢
     */
    public static void insert(Object obj){
        try {

        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    /**
     * 釋放資源的方法
     */
    public static void close(Connection conn, Statement stmt){
        try{
            if(stmt!=null){
                stmt.close();
                stmt = null;
            }
        } catch(SQLException e){
            e.printStackTrace();
        }finally{
            try{
                if(conn!=null){
                    conn.close();
                    conn = null;
                }
            }catch(SQLException e){
                e.printStackTrace();
            }
        }
    }

    public static void close(Connection conn, Statement stmt, ResultSet rs){
        try{
            if(rs!=null){
                rs.close();
                rs = null;
            }
        } catch(SQLException e){
            e.printStackTrace();
        }finally {
            close(conn, stmt);
        }

    }
}