DBUtils的使用

时间:2023-02-07 14:53:55

DButils是apache旗下Commons项目中的一个JDBC工具包,它可以为帮助我们简化对JDBC的操作,但它并不是一个ORM框架,只是可以为我们执行sql,并将返回的ResultSet转化成我们想要的对象。

import com.kastiny.orm.domain.User;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test; import java.io.File;
import java.io.FileFilter;
import java.sql.*;
import java.util.List;
import java.util.Map; public class App { QueryRunner qr = null;
Connection conn = null; @Before
public void before() throws Exception {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/chatroom", "root", "");
qr = new QueryRunner();
} /**
* 获取数据库表中name列的值,并以List返回
* @throws Exception
*/
@Test
public void testGetColumnList() throws Exception {
List<String> ls = (List<String>) qr.query(conn, "select * from user", new ColumnListHandler("name"));
System.out.println(ls);
} /**
* 获取返回记录的的给定字段值,如果没有给定字段则返回第一个字段的值
* 如果返回多条记录,择取第一条记录rs.next();
* @throws Exception
*/
@Test
public void testGetField() throws Exception {
String name = (String) qr.query(conn, "select * from user", new ScalarHandler("name"));
System.out.println(name);
} /**
* 将返回的记录以Map形式返回,【返回的map中key的值会根据执行的sql来定,如果某字段有别名则取用别名,如果没有则使用表的字段名,全部使用小写】
* 如果返回结果包含多条记录,则取其第一条:rs.next();
* return : {id=1, name=aa, pass=aa, addr=安徽, info=hehe, type=0}
* @throws Exception
*/
@Test
public void testSelectMap() throws Exception {
// Map map = qr.query(conn, "select * from user where id=1", new MapHandler());
Map map = qr.query(conn, "select * from user", new MapHandler());
System.out.println(map);
} /**
* 将每条记录转成Map并存放于List
* 结果形式:[{key1:value1,key2:value2},{key1:value1,key2:value2}],
* @throws Exception
*/
@Test
public void testSelectMapList() throws Exception {
List<Map<String, Object>> maps = qr.query(conn, "select * from user", new MapListHandler());
for(Map<String, Object> map : maps) {
System.out.println(map);
}
} /**
* 将返回记录转成指定的对象
* 如果返回结果包含多个记录,则取其第一条:rs.next();
* @throws Exception
*/
@Test
public void testSelectBean() throws Exception {
User user = qr.query(conn, "select * from user where id=1", new BeanHandler<User>(User.class));
System.out.println(user);
} /**
* 将每条记录转成指定的对象并存放于List中
* @throws Exception
*/
@Test
public void testSelectBeanList() throws Exception {
List<User> users = qr.query(conn, "select * from user", new BeanListHandler<User>(User.class));
for(User user : users) {
System.out.println(user);
}
} }

DBUtils对于insert、update操作并没有很好的封装,需要根据sql指定所需的每个值(例:qr.update(conn, "UPDATE user SET NAME = ?, age = ?, address = ? WHERE id = ?", "xxx", 23, "ttt", 5); ),而不可以直接通过Bean进行insert操作。