使用Properties配置數據庫驅動


優點:

  1.   便於修改連接屬性。只需在配置文件中修改,不需要在代碼中修改了。
  2.        更易於維護代碼安全性。

方法:

  • 在src文件嘉下創建database.properties文本文件;添加內容:

  

driver = com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/y1
name=root
password=root
  • 創建工具類MyJDBCUtiles.java,添加代碼:  
package com.kong.JDBCUtils;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class MyJDBCUtiles {
    private MyJDBCUtiles(){}
    private static Connection con;
    private static String driver;
    private static String url;
    private static String name;
    private static String password;
    static{
        try {
            InputStream is = MyJDBCUtiles.class.getClassLoader().getResourceAsStream("database.properties");
            Properties properties = new Properties();
            properties.load(is);
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            name = properties.getProperty("name");
            password = properties.getProperty("password");
            Class.forName(driver);
            con = DriverManager.getConnection(url, name, password);
        }catch (Exception ep){
            throw new RuntimeException(ep+"數據庫連接失敗");
        }
    }
    public static Connection getConnection(){
        return con;
    }
  • 其他類使用時調用即可
        Connection con = MyJDBCUtiles.getConnection();
        System.out.println(con);
  • 輸出結果

完美^_^

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM