2019-06-15 14:21:39
浏览数 (1)
1.编写工具类
代码语言:javascript
复制package cn.javabs.school.util;
import org.apache.commons.dbcp.BasicDataSourceFactory;
import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
public class DbcpUtils {
private static DataSource dataSource;
static String myFile = "dbcp.properties";
static {
try {
InputStream resourceAsStream = DruidUtils.class.getClassLoader().getResourceAsStream(myFile);
Properties p = new Properties();
p.load(resourceAsStream);
// 调用的核心类是BasicDataSourceFactory
dataSource = BasicDataSourceFactory.createDataSource(p);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static DataSource getDataSource(){
return dataSource;
}
public static Connection getConnection(){
try {
return dataSource.getConnection();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
2.编写配置文件:dbcp.properties
代码语言:javascript
复制driverClassName = com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/0314
username=root
password=sorry
3.编写测试类:TestData
代码语言:javascript
复制package cn.javabs.school.test;
import cn.javabs.school.entity.Admin;
import cn.javabs.school.util.DbcpUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.junit.Test;
import java.sql.SQLException;
import java.util.List;
/**
* 测试类: 用于测试数据库是否通畅
* @author Mryang
*/
public class TestData {
QueryRunner qr = new QueryRunner(DbcpUtils.getDataSource());
@Test
public void fun(){
try {
Admin admin = new Admin();
List<Admin> admins = qr.query("select * from admin", new BeanListHandler<Admin>(Admin.class));
System.out.println(admins);
} catch (SQLException e) {
throw new RuntimeException("error:" e);
}
}
}