您的位置:首页 > 数据库

读取properties文件连接数据库

2017-11-12 11:19 309 查看
在properties文件中配置数据库的连接信息(数据库驱动driver、数据库url、用户名和密码),在java类中读取配置参数并连接数据库。

properties文件放在resoure目录下。

db.properties

[java] view
plain copy

driver=com.mysql.jdbc.Driver  

ur
4000
l=jdbc:mysql://localhost/hibernate  

username=root  

password=123456  

编写一个读取properties属性文件的方法类PropertiesUtils

PropertiesUtils.java

[java] view
plain copy

package com.xuxu.util;  

  

import java.io.IOException;  

import java.util.Properties;  

  

public class PropertiesUtils {  

    static Properties property = new Properties();  

    public static boolean loadFile(String fileName){   

        try {  

            property.load(PropertiesUtils.class.getClassLoader().getResourceAsStream(fileName));  

        } catch (IOException e) {  

            e.printStackTrace();  

            return false;     

        }     

        return true;  

    }  

    public static String getPropertyValue(String key){     

        return property.getProperty(key);  

    }  

}  

连接数据库的类DBUtil

DBUtil.java

[java] view
plain copy

package com.xuxu.util;  

  

import java.sql.Connection;  

import java.sql.DriverManager;  

import java.sql.ResultSet;  

import java.sql.SQLException;  

import java.sql.Statement;  

  

public class DBUtil {  

    public Connection conn= null;  

    public Statement stmt= null;  

    public ResultSet rs= null;  

      

    public DBUtil(){}  

      

    public static Connection getConnection(){  

        PropertiesUtils.loadFile("db.properties");  

        String url = PropertiesUtils.getPropertyValue("url");  

        String username = PropertiesUtils.getPropertyValue("username");  

        String password = PropertiesUtils.getPropertyValue("password");    

        String driver = PropertiesUtils.getPropertyValue("driver");    

          

        Connection conn = null;    

        try {  

            Class.forName(driver);  

            conn = DriverManager.getConnection(url,username,password);  

        } catch (ClassNotFoundException e) {  

            e.printStackTrace();  

        } catch (SQLException e) {  

            e.printStackTrace();  

        }  

        if(conn==null){  

            System.out.println("error!!!!!");  

        }  

        return conn;  

    }  

      

    public static void main(String[] args) {  

        System.out.println(DBUtil.getConnection());  

    }  

}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: