代码改变世界

Java jdbc 连接oracle之二(使用properties文件)

2016-12-19 16:33  甘雨路  阅读(4616)  评论(0编辑  收藏  举报
driver = oracle.jdbc.driver.OracleDriver
url = jdbc:oracle:thin:@192.168.10.105:1521:orcl
user = LF
password = LF
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;

import java.util.Properties;

import org.junit.Test;

public class Demo {
    
    
    @Test
    public void test2() throws Exception{
        //IO流读取jdbc.properties文件
        InputStream in = getClass().getClassLoader().getResourceAsStream("jdbc.properties");
        // 读取参数
        Properties p = new Properties();
        p.load(in);
        String driver=p.getProperty("driver");
        String url = p.getProperty("url");
        String user = p.getProperty("user");
        String password = p.getProperty("password");
        // 创建连接(通过反射机制)
        Driver d = (Driver)Class.forName(driver).newInstance();
        // 配置账号密码
        Properties info = new Properties();
        info.put("user", user);
        info.put("password", password);
        // 2 调用driver的connect()方法连接数据库
        Connection con = d.connect(url, info);
        System.out.println(con);
    }
}