代码在下面已经给出 2 种方式查询到的结果一样,那么QueryRunner的无connection是怎样获得连接的???
//需要用到的工具类
public class DBCPUtils {
private static DataSource dataSource;
static{
try {
//1.加载找到properties文件输入流
InputStream is = DBCPUtils.class.getClassLoader().getResourceAsStream("db.properties");
//2.加载输入流
Properties props = new Properties();
props.load(is);
//3.创建数据源 基本数据源工厂
dataSource = BasicDataSourceFactory.createDataSource(props);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static DataSource getDataSource(){
return dataSource;
}
public static Connection getConnection6666(){
try {
return dataSource.getConnection();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
//有Connection 参数的
@Test
public void testQueryAll(){
try {
Connection conn = DBCPUtils.getConnection6666();
QueryRunner qr = new QueryRunner(DBCPUtils.getDataSource());
String sql = "select * from tbl_user";
List<User> users = qr.query(conn, sql, new BeanListHandler<>(User.class));
for (User user : users) {
System.out.println(user.getUname()+" "+user.getUpassword());
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
//没有Connection 参数的
public void testQueryAll1(){
try {
QueryRunner qr = new QueryRunner(DBCPUtils.getDataSource());
String sql = "select * from tbl_user";
List<User> users = qr.query( sql, new BeanListHandler<>(User.class));
for (User user : users) {
System.out.println(user.getUname()+" "+user.getUpassword());
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}