jdbc将数据库连接信息放置配置文件中

目录如下:

jdbcConnection.java:


package jdbc01;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.util.Properties;

import org.junit.Test;
/**
 * 将jdbc连接解耦,放入配置文件中
 * @author sawshaw
 *
 */
public class jdbcConnection{
	public static void main(String[] args) {
		
	}

	public Connection getConnection() throws Exception{
		String driverClass=null;
		String jdbcUrl=null;
		String user=null;
		String pwd=null;
		InputStream in=getClass().getClassLoader().getResourceAsStream("jdbc01/sql.properties");
		//System.out.println("文件地址:"+getClass().getClassLoader().getResource("jdbc01/sql.properties"));
		//System.out.println("文件地址:"+getClass().getClassLoader().getSystemResource("jdbc01/sql.properties"));
		Properties properties=new Properties();
		properties.load(in);
		driverClass=properties.getProperty("driver");
		jdbcUrl=properties.getProperty("url");
		user=properties.getProperty("user");
		pwd=properties.getProperty("pwd");
		//forName 返回一个类,newInstance创建一个对象
		Driver driver=(Driver) Class.forName(driverClass).newInstance();
		Properties info=new Properties();
		info.put("user",user);
		info.put("password",pwd);
		Connection connection=driver.connect(jdbcUrl, info);
		return connection; 
	}
	
	@Test 
	public void testConnection() throws Exception{
		System.out.println(getConnection());
	}
}

 sql.properties:


driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
user=root
pwd=root

用Junit测试通过,连接成功。。。

 

posted @ 2015-11-24 23:13  Lost blog  阅读(2825)  评论(0编辑  收藏  举报