package com.xt.test;


import java.io.InputStream;

import java.sql.SQLException;

import java.util.Properties;


import org.junit.Test;


import com.mysql.jdbc.Connection;

import com.mysql.jdbc.Driver;

/**

 * 测试连接数据库,获取数据库链接

 * 其中有读取资源文件的方法。

 * @author LZF

 */

public class TestDBConnection {

/**

* 直接硬编码连接mysql

* @throws SQLException

*/

@Test

public void testJdbc() throws SQLException{

Driver driver=new com.mysql.jdbc.Driver();

String url="jdbc:mysql://127.0.0.1:3306/test";

Properties info=new Properties();

info.put("user", "root");

info.put("password", "");

Connection connection=(Connection) driver.connect(url, info);

System.out.println(connection);

}

/**

* 通过配置,将数据库的基本信息放置到配置文件中。

* @throws ClassNotFoundException 

* @throws IllegalAccessException 

* @throws InstantiationException 

* @throws SQLException

*/

public Connection getConnection() throws Exception{

//读取类路径下的jdbc.properties

InputStream      in=getClass().getClassLoader().getResourceAsStream("jdbc.properties");

Properties properties=new Properties();

properties.load(in);

String driverClass=properties.getProperty("driverClass");

String jdbcUrl=properties.getProperty("jdbcUrl");

String userName=properties.getProperty("userName");

String password=properties.getProperty("password");

if(password==null&&"".equals(password)){

password="";

}

Properties info=new Properties();

info.put("user", userName);

info.put("password", password);

//通过反射创建对象

Driver driver=(Driver)Class.forName(driverClass).newInstance();

Connection connection=(Connection) driver.connect(jdbcUrl, info);

return connection;

}

@Test

public void testGetConnection() throws Exception{

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

}

}