DbUtils类
ResultSetHandler 接口
MapListHandler 类 (实现ResultSetHandler 接口)把从数据库中查询出的记录 都 放到List 集合当中, List集合中每一个对象都是Map类型,可以根据这条记录的字段名读出相对应的值
BeanListHandler 类 (实现ResultSetHandler 接口)把从数据库中的记录 放到List集合中 ,List集合中每一个对象都是一个JavaBean类型的对象,可以根据get 方法得到值
QreryRunner类 值行SQL语名,其中一个参数为以上两种类型的对象
- import java.sql.Connection;
- import java.sql.SQLException;
- import java.util.List;
- import javax.naming.Context;
- import javax.naming.InitialContext;
- import javax.naming.NamingException;
- import javax.sql.DataSource;
- import org.apache.commons.dbutils.QueryRunner;
- import org.apache.commons.dbutils.ResultSetHandler;
- /**
- * 该类主要完成对数据库的操作
- *
- */
- public class SqlUtil {
- private static String datasoucename ="java:comp/env/jdbc/exam";
- private DataSource da;
- private static sqlUtil sqlutil = null;
- public static sqlUtil newInstance()
- {
- if(sqlutil == null) {
- sqlutil = new sqlUtil();
- }
- return sqlutil;
- }
- public Connection getConnection() throws SQLException
- {
- synchronized (da) {
- return da.getConnection();
- }
- }
- /**
- * 构造方法,设置数据源
- * @param datasoucename
- */
- private sqlUtil() {
- init();
- }
- /**
- * 初始化数据源的方法
- */
- private void init() {
- try {
- Context ct = new InitialContext();
- this.da = (DataSource) ct.lookup(datasoucename);
- ct.close();
- } catch (NamingException e) {
- e.printStackTrace();
- }
- }
- /**
- * 对数据增删改的方法,需要一个object的数组,数据是sql语句的占位符
- * @param sql
- * @param pring
- * @return
- */
- public boolean update(String sql, Object pring[]) {
- QueryRunner qu = new QueryRunner();
- int i = 0;
- boolean flag = false;
- try {
- i = qu.update(getConnection(),sql, pring);
- if(i>=0){
- flag = true;
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
- return flag;
- }
- /**
- * 对数据查找的方法,需要一个objece的数组,数据是sql语句的占位符,ResultSetHandler参数是你要把查询出的数据转换的类型
- * 可以是一个javabean (如:new BeanListHandler (JavaBean.class)或:new MapListHandler )
- * @param sql
- * @param pring 参数数组可以为空
- * @param rsh
- * @return
- */
- public List query(String sql, Object pring[], ResultSetHandler rsh) {
- QueryRunner qu = new QueryRunner();
- List result = null;
- try {
- result = (List) qu.query(getConnection(),sql, pring, rsh);
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return result;
- }
- }
调用
- /**
- * 删除
- * @return boolean
- * @param ItemPool的Id
- */
- public boolean deteItemPool(String ipId) {
- String sql1 = "delete from ItemPool where ipId =? ";
- //指定所需要的参数 数组
- Object[] pring = {ipId};
- //执行更新
- boolean result = sql.update(sql1, pring);
- return result;
- }
- /**
- * 根据题库Id查找题库的方法
- */
- public ItemPool searchItemPoolById(String ipId) {
- String sql1 = "select * from ItemPool where ipId=?";
- //指定参数数组
- Object[] pring = {ipId};
- List list = sql.query(sql1, pring, new BeanListHandler(ItemPool.class));
- ItemPool itempool=(ItemPool)list.get(0);
- return itempool;
- }