DbUtil工具的使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhang__l/article/details/51920672

1、项目所用到的包:



<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>


<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.3</version>
</dependency>


<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>


<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2</version>
</dependency>


2、DataSourceUtil工具类:保证管理一个datasource数据源



public class DataSourceUtil {
private DataSourceUtil() {
}


private static DataSource ds = null;


static {
Properties properties = new Properties();
try {
properties.load(DataSourceUtil.class.getClassLoader().getResourceAsStream("jdbc.properties"));
ds = new BasicDataSourceFactory().createDataSource(properties);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}


/**
* 获取数据源
*/
public static DataSource getDataSource() {
return ds;

}

3、测试




public class TestDbUtil {


private DataSource ds;


@Before
public void before() throws Exception {
ds=DataSourceUtil.getDataSource();
}


@Test
public void testInsert() throws Exception {
QueryRunner qr=new QueryRunner(ds);
String sql="insert into t_user(name,password) values('tom','ttt')";
qr.update(sql);
}
@Test
public void testInsert2() throws Exception {
QueryRunner qr=new QueryRunner(ds);
String sql="insert into t_user(name,password) values(?,?)";
qr.update(sql,"tom2","ttt2");
}

@Test
public void testQuery1() throws Exception {
QueryRunner qr=new QueryRunner(ds);
Object[] array = qr.query("select * from t_user", new ArrayHandler());
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
}
@Test
public void testQuery2() throws Exception {
QueryRunner qr=new QueryRunner(ds);
User user = qr.query("select id,name,password as pwd from t_user", new BeanHandler<User>(User.class));
System.out.println(user);
}
@Test
public void testQuery3() throws Exception {
QueryRunner qr=new QueryRunner(ds);
List<User> users = qr.query("select id,name,password as pwd from t_user", new BeanListHandler<User>(User.class));
System.out.println(users);
}
/**
* @throws Exception
*/
@Test
public void testQuery4() throws Exception {
QueryRunner qr=new QueryRunner(ds);
List<User> users = qr.query("select * from t_user ", new ResultSetHandler<List<User>>() {


public List<User> handle(ResultSet rs) throws SQLException {
List<User> users=new ArrayList<User>();

while (rs.next()) { 
int id = rs.getInt("id");
String name = rs.getString("name");
String password = rs.getString("password");
users.add(new User(id, name, password));
}
return users;
}
});
System.out.println(users);

}


猜你喜欢

转载自blog.csdn.net/zhang__l/article/details/51920672