junit链接mysql_获取数据库链接Junit

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());

}

}

本文转自lzf0530377451CTO博客,原文链接:http://blog.51cto.com/8757576/1544454 ,如需转载请自行联系原作者

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值