如何通过配置文件链接数据库?

来源:互联网 发布:拇指特效软件 编辑:程序博客网 时间:2024/06/07 12:01

配置文件jdbc.properties

##MySQLdriver=com.mysql.jdbc.Driverurl=jdbc\:mysql\:///ake?useUnicode\=true&characterEncoding\=UTF-8username=rootpassword=1234##Oracle#driver=oracle.jdbc.driver.OracleDriver#url=jdbc:oracle:thin:@127.0.0.1:1521:orcl#username=scott#password=tiger

简单的讲一下。配置文件写了MySQL和Oracle的数据库信息,我的数据库是MySQL 所以我把Oracle的配置信息注释掉了。

接下来就是一个单例(饿汉式)的获得数据库连接方法工具类

package Studying.d15;import java.io.FileInputStream;import java.sql.Connection;import java.sql.DriverManager;import java.util.Properties;public class ConnUtils {    private static Connection con = null;    static{        try {            Properties p = new Properties();            p.load( new FileInputStream("jdbc.properties") );            String driver = p.getProperty("driver");            String url = p.getProperty("url");            String username = p.getProperty("username");            String password = p.getProperty("password");            System.out.println(url+","+driver);            Class.forName(driver);            con = DriverManager.getConnection(url, username, password);        } catch (Exception e) {            e.printStackTrace();        }    }    public static Connection getConnection(){        return con;    }}