利用反射对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 blocke.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 blocke.printStackTrace();} catch (InstantiationException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalArgumentException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (InvocationTargetException e) {// TODO Auto-generated catch blocke.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("," + "?");// System.out.println(field.get(bif));}sql.append(")");sqlvalue.append(")");sql.append(sqlvalue);String sqled = sql.toString();//System.out.println(sqled);pstmt = getConnection().prepareStatement(sqled);for (int i = 0; i < fields.length; i++) {Field field = fields[i];field.setAccessible(true);getType(pstmt, field.get(bif), i + 1);}pstmt.executeUpdate();flag = "success";} catch (IllegalArgumentException e) {// TODO Auto-generated catch blockflag = "error";// e.printStackTrace();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {CloseAll();}return flag;}// 删除/* * obj 实体类名 * culmName 要删除的列值名 * culmValue 要删除的列值值 * */public String delete(Object obj,String culmName,Object culmValue) {String flag = "";Class<? extends Object> clazz = obj.getClass();String classname = obj.getClass().getName().substring(obj.getClass().getName().lastIndexOf(".") + 1,obj.getClass().getName().length());// 截取类名String sql = "delete from " + classname + " where "+culmName+" = " + culmValue;try {pstmt = getConnection().prepareStatement(sql);pstmt.execute();System.out.println(sql);flag = "success";} catch (SQLException e) {// TODO Auto-generated catch blockflag = "error";// e.printStackTrace();} finally {CloseAll();}return flag;}/* * obj 要更新的类名 * updatakeyName 索引列值名 * keyValue 索引列值值 * updataculmName 要更新的列值 * culmValue 要更新的列值值 */public String updateByculm(Object obj,String updatakeyName,Object keyValue,String updataculmName,Object culmValue) throws SQLException{String flag ="";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());// 截取类名String sql ="update "+classname+" set "+updataculmName+" = '"+culmValue+"' where "+updatakeyName+" = "+keyValue;//System.out.println(sql);pstmt = getConnection().prepareStatement(sql);pstmt.executeUpdate();CloseAll();return flag;}// 执行SQL语句public String executSQL(String sql) {String flag = "";try {stmt = getConnection().createStatement();stmt.execute(sql);flag = "success";} catch (SQLException e) {// TODO Auto-generated catch blockflag = "error";e.printStackTrace();} finally {CloseAll();}return flag;}// 关闭连接public void CloseAll() {try {if (rs != null) {rs.close();}if (stmt != null) {stmt.close();}if(pstmt !=null){pstmt.close();}if (conn != null) {conn.close();}} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}// 判断插入参数类型public void getType(PreparedStatement pstmt, Object obj, int i)throws SQLException {if (obj instanceof java.util.Date) {java.util.Date dates = (java.util.Date) obj;java.sql.Date date = new java.sql.Date(dates.getTime());pstmt.setDate(i, date);} else {pstmt.setObject(i, obj);}}}