日期:2014-05-16  浏览次数:20371 次

封装jdbc
package com.lxit.sys.work.dbUtil;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;

import com.lxit.sys.work.servlet.ActionServlet;
import com.lxit.sys.work.transaction.Transaction;

/**
 * 处理dao层类
 *
 */
public class DAOHelper {
private final Logger logger = Logger.getLogger(ActionServlet.class);


单个查询,返回单个对象
	public Object get(String sql,Class<?> cls,Object ...objects) {
		List<Object> list = listObj(sql, cls, objects);
		System.out.println("size"+list.size());
		if(list.size()>0){
			System.out.println("123");
			return list.get(0);
		}
		return null;
	}


查询全部
	public List<Object> listObj(String sql,Class<?> cls,Object ...objects) {
		logger.debug("dao帮助层开始执行......."+cls);
		List<Object> list = new ArrayList<Object>();
		Connection conn = DBUtil.getDBUtil().getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			System.out.println("sql语句==="+sql);
			ps=conn.prepareStatement(sql);
			rs=ps.executeQuery();
			ResultSetMetaData rm = rs.getMetaData();
			int column = rm.getColumnCount();
			String[] coluName = new String[column];
			for(int i=1;i<=column;i++){
				coluName[i-1]=rm.getColumnName(i);
			}
			logger.debug("dao层开始执行中  ");
			while(rs.next()){
				Object obj = cls.newInstance();
				for(int i=0;i<coluName.length;i++){
					BeanUtils.setProperty(obj, coluName[i], rs.getObject(coluName[i]));
				}
				list.add(obj);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		}finally{
			DBUtil.getDBUtil().close(ps, rs);
		}
		logger.debug("dao层开始执行完成....list=="+list.toString());
		return list;
	}
[color=blue]增、删、修[/color]
	public int update(String sql) {
		Connection conn = Transaction.getConnection();
		Statement ps = null;
		int  row = -1;
		try {
			ps=conn.createStatement();
			row=ps.executeUpdate(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return row;
	}
}

上面例子:简单对jdbc封装下,只需要传入一条sql语句,适用于所有的增删查改。
注:数据库的字段要于属性类的一致;