maven 构建 mysql数据库利用 properties连接

//这里是 properties文件读取工具
public class PropertiesUtil {
    static Properties properties = new Properties();

    public PropertiesUtil() {
    }
    public static boolean loadFile(String fileName){
        try {
            properties.load(PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName));
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    public static String getPropertyValue(String key){
        return properties.getProperty(key);
    }
}
//通过上面的工具就可以获取到properties文件中的键值从而可以加载驱动 获取链接 从而 可以增删改查
    private  Connection conn = null;


    public Connection getConn(){
        PropertiesUtil.loadFile("db.properties");
        String driver = PropertiesUtil.getPropertyValue("driver");
        String url = PropertiesUtil.getPropertyValue("url");
        String username  = PropertiesUtil.getPropertyValue("username");
        String password = PropertiesUtil.getPropertyValue("");

        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url,username,password);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
            close();
        }
        return conn;
    }
    public  void close(){
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


//prperties文件
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost/student
username=root
password=

你可能感兴趣的:(javaweb)