1.编写工具类
package cn.javabs.school.util; import com.alibaba.druid.pool.DruidDataSourceFactory; import javax.sql.DataSource; import java.io.InputStream; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; public class DruidUtils { private static DataSource dataSource; static String myFile = "druid.properties"; static { try { InputStream resourceAsStream = DruidUtils.class.getClassLoader().getResourceAsStream(myFile); Properties p = new Properties(); p.load(resourceAsStream); dataSource = DruidDataSourceFactory.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.编写配置文件:druid.properties
driverClassName = com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/0314 username=root password=sorry
3.编写测试类:TestData
package cn.javabs.school.test; import cn.javabs.school.entity.Admin; import cn.javabs.school.util.DruidUtils; 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(DruidUtils.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); } } }