DBUtils

上次学到dbcp或者c3p0可创建连接池,但是Connection创建了,用什么来访问数据呢,答案是:DBUtils进行CRUD操作即可。

QueryRunner类

顾名思义,该类是用来执行Query语句的。其中构造方法有
QueryRunner() //不带事务的话,用这个就可以啦。
QueryRunner(DataSource ds) //如果用到事务,则需要带datasource的构造器。

删除、追加、修改

Connection conn = DBUtils.getConnection();
String delete = "delete from student where name=?";
String insert = "insert into student (name) values(?)";
String modify = "update student set name=? where id=?";

//执行sql语句
QueryRunner queryRunner = new QueryRunner();
queryRunner.update(conn, insert, "hello");
queryRunner.update(conn, delete, "hello");

原始方式查询

String sql=“select name from student where id=?”;
DBUtils将PreparedStatement进行封装,不需要用户自己进行繁琐的处理。
在查询中只需要通过实现ResultSetHandler接口,实现handle方法,处理ResultSet即可。
query(Connection conn, String sql, ResultSetHandler rsh, param1, param2)
public class DBUtilsTest {
	public static void main(String[] args) throws Exception{
		Connection conn = DAO.getConnection();
		QueryRunner queryRunner = new QueryRunner();
		
		String sql = "select name, sex, age from student where id=";	
		class MyResultSetHandler implements ResultSetHandler>{
			@Override
			public List handle(ResultSet arg0) throws SQLException {
				List list = new ArrayList();
				while(arg0.next())
				{
					Student s = new Student(arg0.getString(1), arg0.getString(2), arg0.getInt(3));
					list.add(s);
				}
				return list;
			}
		}
		
		List rs= queryRunner.query(conn, sql, new MyResultSetHandler());
		for(Student s:rs){
			System.out.println(s);
		}
	}
}

高级的BeanHandler举例

上面说的实现ResultSetHanlder,其实在DBUtils中已经有很多默认的实现方法,用起来更方便。
BeanHandler,返回记录中的第一条记录,并且转为指定的Bean对象。
※注意:由于BeanHandler是通过反射来创建对应类的,所以指定的类必须有一个public的无参构造器。
public class DBUtilsTest 
{
	public static void main(String[] args) throws Exception{
		Connection conn = DAO.getConnection();
		QueryRunner queryRunner = new QueryRunner();
		
		String sql = "select name, sex, age from student where id=?";	
		Student rs= queryRunner.query(conn, sql, new BeanHandler(Student.class), 3);
		System.out.println(rs);
	}
}

BeanListHandler举例:

public class DBUtilsTest  {
	public static void main(String[] args) throws Exception{
		Connection conn = DAO.getConnection();
		QueryRunner queryRunner = new QueryRunner();
		
		String sql = "select name, sex, age from student";	
		List rs= queryRunner.query(conn, sql, new BeanListHandler(Student.class));
		System.out.println(rs);
	}
}

MapHandler,MapListHandler

也可以不用集合,用MapHandler,MapListHandler返回键值对的形式。代码和上面一样不再重复。
{name=student1, sex=Female, age=20}

ScalarHandler,返回一个单个值。

public class DBUtilsTest  {
	public static void main(String[] args) throws Exception{
		Connection conn = DAO.getConnection();
		QueryRunner queryRunner = new QueryRunner();
		
		String sql = "select count(id) from student";	
		Long rs= queryRunner.query(conn, sql, new ScalarHandler(), 3);
		System.out.println(rs);
	}
}

<完>

你可能感兴趣的:(java笔记)