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

利用反射对JDBC封装

通用的SQL增删改查语法,但是还是存在着很多很多问题,例如查询返回时数据库类型和实体类类型匹配不上而无法赋值等等问题

?

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class UniversalSQL {

	Statement stmt = null;
	PreparedStatement pstmt = null;
	ResultSet rs = null;
	Connection conn = null;
	String driver;
	String url;
	String username;
	String password;

	public UniversalSQL(String driver, String url, String username,
			String password) {
		this.driver = driver;
		this.url = url;
		this.username = username;
		this.password = password;
		
	}
	
	
	public Connection getConnection(){
		try {
			
			Class.forName(driver);
			conn = DriverManager.getConnection(url, username, password);
		} catch (SQLException ex1) {// catch出错
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return conn;
	}

	// 查找全部
	public <E> List<E> findAll(Object obj) throws SQLException {

		List<E> list = null;
		E newInstance = null;
		Class<? extends Object> clazz = obj.getClass();
		Field[] fields = clazz.getDeclaredFields();// 获取类定义的属性
		String classname = obj.getClass().getName().substring(
				obj.getClass().getName().lastIndexOf(".") + 1,
				obj.getClass().getName().length());// 截取类名

		Method[] methods = clazz.getDeclaredMethods();

		String sql = "select * from " + classname;
		try {
			pstmt = getConnection().prepareStatement(sql);
			rs = pstmt.executeQuery();
			while (rs.next()) {
				newInstance = (E) clazz.newInstance();// 实例化一个传进来的对象
				for (Method method : methods) {
					
					if (method.getName().substring(0, 3)
							.equalsIgnoreCase("set")) {
						
						String s = method.toString();
						s = s.substring(s.indexOf("(")+1, s.indexOf(")"));
						Object object = null;
						if("java.util.Date".equals(s)){
							object = rs.getDate(method.getName()
									.substring(3));
						}else{
							 object = rs.getObject(method.getName()
									.substring(3));
						}
						if (object != null) {
							
							method.invoke(newInstance, object);// 给对象参数赋值
						}
					}
				}// 完成对一个类所有参数赋值
				if (list == null) {
					list = new ArrayList<E>();
				}
				list.add(newInstance);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			CloseAll();
		}
		return list;
	}

	// 插入数据
	public <E> String save(Object bif) {

		String flag = "";
		E newInstance = null;
		Object obj = bif;
		Class<? extends Object> clazz = obj.getClass();

		String classname = obj.getClass().getName().substring(
				obj.getClass().getName().lastIndexOf(".") + 1,
				obj.getClass().getName().length());// 截取类名

		// 开始拼接预调用插入语句
		StringBuffer sql = new StringBuffer();
		sql.append("insert into ");
		sql.append(classname + "(");
		Field[] fields = clazz.getDeclaredFields();
		StringBuffer sqlvalue = new StringBuffer(" values (");

		try {
			if (fields.length > 0) {
				sql.append(fields[0].getName());
				fields[0].setAccessible(true);
				sqlvalue.append("?");
			}
			for (int i = 1; i < fields.length; i++) {
				Field field = fields[i];
				sql.append("," + field.getName());
				field.setAccessible(true);
				sqlvalue.append("," + "?");