这是在下初学j2se的一个小作业,用反射机制和事务机制写的jdbc操作类库框架(增、删、改、查)
开发环境dom4j,jdk1.5
需要
jdbc.util包内文件
(
1.Commond.java
2.Script.java
3.XMLVisitor.java
)
jdbc.dal数据操作层
jdbc.bll业务逻辑层
commond.java
package jdbc.util; public interface Commond { //public static final String WEBCONFIG="/WEB-INF/SqlMapConfig.xml";//xml配置文件索引 public static final String DRIVER_URL="com.mysql.jdbc.Driver"; public static final String URL="jdbc:mysql://localhost/scm"; public static final String USER="root"; public static final String PASSWORD="123456"; }
Script.java
package jdbc.util; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Iterator; import java.util.List; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import sun.util.calendar.BaseCalendar; import sun.util.calendar.CalendarDate; import sun.util.calendar.CalendarSystem; public class Script { /** * path为XML文件路径,根据节点名称nodeName中的第index个属性比较value,返回所找到的element * nodeName为空时返回根节点 * * @param path * @param nodeName * @param index * @param value * @return */ public static Element getElementFromXML(String path, String nodeName, int index, String value) { Element e = null; SAXReader reader = new SAXReader(); File file = new File(path); try { Document d = reader.read(file); e = d.getRootElement(); if (!nodeName.equals("")) { XMLVisitor arg0 = new XMLVisitor(e, nodeName, 0, value); d.accept(arg0); e = arg0.getElement(); } } catch (DocumentException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } return e; } /** * 将XML数据导入到TableModel * * @param table * @param path * @return */ public static DefaultTableModel XMLtoTableModel(DefaultTableModel table, String path) { DefaultTableModel value = null; SAXReader sr = new SAXReader(); File file = new File(path); Element e = null; List<Attribute> ablist = null; Object dataVector[][] = null; Object[] columnIdentifiers = null; Object[] rowData = null; try { Document d = sr.read(file); Iterator it = d.nodeIterator(); if (it.hasNext()) { e = (Element) it.next(); List<Element> list = e.elements(); // 得到表头 columnIdentifiers = new Object[list.get(0).attributeCount()]; for (int i = 0; i < list.get(0).attributeCount(); i++) { ablist = list.get(0).attributes(); columnIdentifiers[i] = ablist.get(i).getName(); // System.out.println(columnIdentifiers[i]); } // System.out.println(columnIdentifiers.length); rowData = new Object[list.get(0).attributeCount()]; dataVector = new Object[list.size()][list.get(0) .attributeCount()]; for (int i = 0; i < list.size(); i++) { e = list.get(i); ablist = e.attributes(); // System.out.println(e.getName()); for (int j = 0; j < ablist.size(); j++) { dataVector[i][j] = ablist.get(j).getValue(); rowData[j] = ablist.get(j).getValue(); // System.out.println(ablist.get(j).getName()+" "+ablist.get(j).getValue()); } if (isExist(rowData[0], table)) continue; /** * 数据筛选 */ if (!rowData[0].toString().matches("//d*"))// 检测id { continue; } if (!rowData[1].toString().matches("//d*"))// 检测职工号 { continue; } if (rowData[3].toString().matches("//w*"))// 检测性别 { continue; } if (!rowData[4].toString().matches("//w*"))// 检测部门 { continue; } if (!rowData[5].toString().matches("//d*"))// 检测工资 { continue; } table.addRow(rowData); } value = new DefaultTableModel(dataVector, columnIdentifiers); } } catch (DocumentException ex) { // TODO Auto-generated catch block ex.printStackTrace(); } return value; } private static boolean isExist(Object object, DefaultTableModel table) { // TODO Auto-generated method stub boolean value = false; String tmp = (String) object; for (int i = 0; i < table.getRowCount(); i++) { if (table.getValueAt(i, 0).toString().equals(tmp)) value = true; } return value; } /** * 将tablemodel导出到xml中,path为文件路径 * * @param table * @param path * @return */ public static boolean tableModelToXML(JTable table, String path) { boolean value = false; int row = table.getRowCount(); int column = table.getColumnCount(); Document d = DocumentHelper.createDocument(); Element root = null; // if (!table.getName().toString().equals("")) { // root = d.addElement(table.getName());// 将表名设置为根目录 // } else { root = d.addElement("root"); // } Element data = null; for (int i = 0; i < row; i++) { data = root.addElement("data"); for (int j = 0; j < column; j++) { data.addAttribute(table.getColumnName(j).toString(), table .getValueAt(i, j).toString()); } } File file = new File(path); FileWriter writer = null; try { writer = new FileWriter(file); OutputFormat format = new OutputFormat(); format.setEncoding("GBK"); XMLWriter wout = new XMLWriter(writer, format); // d.setXMLEncoding("GBK"); wout.write(d); wout.flush(); wout.close(); value = true; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return value; } /** * 返回格式化后的当前时间,格式(2009-8-1 12:00:00) * * @return */ public static String getDateTimeNow() { StringBuffer value = new StringBuffer(); BaseCalendar base = CalendarSystem.getGregorianCalendar(); CalendarDate date = base.getCalendarDate(); value.append(date.getYear()); value.append("-"); value.append(date.getMonth()); value.append("-"); value.append(date.getDayOfMonth()); value.append(" "); if (("" + date.getHours()).length() == 1) { value.append("0" + date.getHours()); } else { value.append(date.getHours()); } value.append(":"); if (("" + date.getMinutes()).length() == 1) { value.append("0" + date.getMinutes()); } else { value.append("" + date.getMinutes()); } value.append(":"); if (("" + date.getSeconds()).length() == 1) { value.append("0" + date.getSeconds()); } else { value.append(date.getSeconds()); } return value.toString(); } /** * 去除非法字符 * * @param str * @return */ public static String replace(String str) { String value = ""; value = str.replace("'", ""); value = value.replace("?", ""); value = value.replace("!", ""); value = value.replace("//", ""); value = value.replace("|", ""); value = value.replace("%", ""); return value; } /** * MD5 加密 * * @param str * @return */ public static String getMD5Str(String str) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(str.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); System.exit(-1); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append( Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } return md5StrBuff.toString(); } }
XMLVisit.java
package jdbc.util; import org.dom4j.Attribute; import org.dom4j.CDATA; import org.dom4j.Comment; import org.dom4j.Document; import org.dom4j.DocumentType; import org.dom4j.Element; import org.dom4j.Entity; import org.dom4j.Namespace; import org.dom4j.ProcessingInstruction; import org.dom4j.Text; import org.dom4j.Visitor; public class XMLVisitor implements Visitor { private Element element = null; private String value = "";//值 private int index=0;//属性索引 private String nodeName="";//节点名字 /** * 将节点名称nodeName中的第index个属性值与value比较,返回element * @param e * @param nodeName * @param index * @param value */ public XMLVisitor(Element e,String nodeName,int index, String value) { // TODO Auto-generated constructor stub this.element = e; this.value = value; this.index=index; this.nodeName=nodeName; } public void visit(Document arg0) { // TODO Auto-generated method stub } public void visit(DocumentType arg0) { // TODO Auto-generated method stub } public void visit(Element arg0) { // TODO Auto-generated method stub if (arg0.getName().equals(nodeName)) { if (((Attribute) (arg0.attributes().get(index))).getValue().equals(value)) { element = arg0; return; } } } public Element getElement() { return element; } public void visit(Attribute arg0) { // TODO Auto-generated method stub } public void visit(CDATA arg0) { // TODO Auto-generated method stub } public void visit(Comment arg0) { // TODO Auto-generated method stub } public void visit(Entity arg0) { // TODO Auto-generated method stub } public void visit(Namespace arg0) { // TODO Auto-generated method stub } public void visit(ProcessingInstruction arg0) { // TODO Auto-generated method stub } public void visit(Text arg0) { // TODO Auto-generated method stub } }
jdbc.dal.DbHelperSql.java
package jdbc.dal; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.sql.Connection; 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 jdbc.util.Commond; import org.dom4j.Element; /** * 数据操作 table:student * * @author XudongChen * */ public class DbHelperSql<T> { private Connection conn = null;// 数据库连接 private PreparedStatement pst = null; private ResultSet rs = null; private Element e = null; public DbHelperSql() { init(); } /** * 初始化操作 */ private void init() { try { Class.forName(Commond.DRIVER_URL); // String path=Commond.WEBCONFIG; // String nodeName=""; // int index=0; // String value=""; // e=Script.getElementFromXML(path, nodeName, index, value);//搜索根目录 // nodeName="sqlMap"; // value=e.attributeValue("value");//返回根目录属性 // // //搜索对应数据库配置文件 // e=Script.getElementFromXML(path, nodeName, index, value); // // path=e.attributeValue("resource");//读取配置文件地址 // nodeName="add";//搜索节点 // value=e.attributeValue("value");//关键字 // e=Script.getElementFromXML(path, nodeName, index, value); // Class.forName(e.attributeValue("driverClassName")); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 连接数据库,连接成功返回true,否则返回false * * @return boolean */ private boolean connection() { boolean value = false; try { conn = DriverManager.getConnection(Commond.URL, Commond.USER, Commond.PASSWORD); // String url=e.attributeValue("url"); // String user=e.attributeValue("username"); // String password=e.attributeValue("password"); // conn=DriverManager.getConnection("jdbc:mysql://localhost/table", // "root", "123456"); value = true; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return value; } /** * 关闭数据库 */ private void close() { try { if (rs != null) { rs.close(); rs = null; } if (pst != null) { pst.close(); pst = null; } if (conn != null) { conn.close(); conn = null; } } catch (Exception ex) { ex.printStackTrace(); } } private void clear() { try { if (rs != null) { // rs.close(); rs = null; } if (pst != null) { // pst.close(); pst = null; } if (conn != null) { // conn.close(); conn = null; } } catch (Exception ex) { ex.printStackTrace(); } } public boolean update(Class c, Object model) { boolean value = false; StringBuffer str = new StringBuffer(); // str.append("update student " + "set name=?," + " age=? " + // "where id=?"); str.append("update " + c.getSimpleName()); str.append(" set " + updateContentStr(model)); str.append(" where " + updateContentWhere(model)); try { this.connection(); pst = conn.prepareStatement(str.toString()); // pst.setString(1, student.getName()); // pst.setInt(2, student.getAge()); // pst.setInt(3, student.getId()); pst.executeUpdate(); value = true; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("出错sql:" + str); } finally { this.close(); } return value; } /** * update中的where条件 * * @param model * @return */ private String updateContentWhere(Object model) { String value = ""; Class c = model.getClass(); Field[] field = c.getDeclaredFields(); value = getFieldMethod(field[0].getName()); try { Method method = c.getMethod(value, null); value = field[0].getName() + "=" + method.invoke(model, null); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return value; } /** * 获取update set内容 * * @param model * @return */ private String updateContentStr(Object model) { String value = ""; String fieldmethod = "";// Class c = model.getClass(); Field[] field = c.getDeclaredFields(); Method method = null;// try { for (int i = 0; i < field.length - 1; i++) { fieldmethod = getFieldMethod(field[i].getName());// method = c.getMethod(fieldmethod, null);// if (field[i].getType().getSimpleName().equals("String")) { value += field[i].getName() + "=" + "'" + method.invoke(model, null) + "',"; } else { value += field[i].getName() + "=" + method.invoke(model, null) + ","; } } fieldmethod = getFieldMethod(field[field.length - 1].getName());// method = c.getMethod(fieldmethod, null);// if (field[field.length - 1].getType().getSimpleName().equals( "String")) { value += field[field.length - 1].getName() + "=" + "'" + method.invoke(model, null) + "'"; } else { value += field[field.length - 1].getName() + "=" + method.invoke(model, null) + ""; } } catch (Exception e) { e.printStackTrace(); } return value; } /** * 根据主键并通过反射机制判断这条记录是否存在,存在则返回true,不存在则返回false; * * @param c * @param id * @return */ public boolean isExist(Class c, int id) { boolean value = false; StringBuffer strSql = new StringBuffer(); try { this.connection(); Field[] field = c.getDeclaredFields(); strSql.append("select count(" + field[0].getName() + ") as countid from "); strSql.append(c.getSimpleName()); strSql.append(" where " + field[0].getName() + "=?"); pst = conn.prepareStatement(strSql.toString()); pst.setInt(1, id); rs = pst.executeQuery(); rs.next(); if (rs.getInt("countid") == 1) { value = true; } } catch (Exception e) { // TODO: handle exception } finally { this.close(); } return value; } /** * 事务机制和反射机制的多表增加操作 * @param c 数据库的表集合 * @param model 数据model * @param sqllist 其他还需要执行的sql语句 * @return 操作结果状态(true,false) */ public boolean add(ArrayList<Class> c, ArrayList<Object> model,ArrayList<String> sqllist) { boolean value = false; StringBuffer strSql = null; this.connection(); Statement csm = null; try { conn.setAutoCommit(false); csm = conn.createStatement(); for (int i = 0; i < model.size(); i++) { strSql = new StringBuffer(); strSql.append("insert into "); strSql.append(c.get(i).getSimpleName() + "(" + getModelField(c.get(i)) + ")"); // strSql.append(c.getSimpleName()); strSql.append(" values "); strSql.append(contentStr(model.get(i))); System.out.println("sql:" + strSql); csm.addBatch((strSql.toString())); //pst.executeUpdate(); } for(int i=0;i<sqllist.size();i++) { csm.addBatch(sqllist.get(i)); } csm.executeBatch(); conn.commit(); value = true; conn.setAutoCommit(true); } catch (SQLException e) { // TODO Auto-generated catch block try { conn.rollback(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } e.printStackTrace(); } finally { this.close(); } return value; } /** * 通过事务机制和反射机制,增加对应表中的数据 * @param c * @param model * @return */ public boolean add(ArrayList<Class> c, ArrayList<Object> model) { boolean value = false; StringBuffer strSql = null; this.connection(); Statement csm = null; try { conn.setAutoCommit(false); csm = conn.createStatement(); for (int i = 0; i < model.size(); i++) { strSql = new StringBuffer(); strSql.append("insert into "); strSql.append(c.get(i).getSimpleName() + "(" + getModelField(c.get(i)) + ")"); // strSql.append(c.getSimpleName()); strSql.append(" values "); strSql.append(contentStr(model.get(i))); System.out.println("sql:" + strSql); csm.addBatch((strSql.toString())); // pst.executeUpdate(); } csm.executeBatch(); conn.commit(); value = true; conn.setAutoCommit(true); } catch (SQLException e) { // TODO Auto-generated catch block try { conn.rollback(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } e.printStackTrace(); } finally { this.close(); } return value; } /** * 通过反射添加一条记录 * * @param c * @param model */ public void add(Class c, Object model) { StringBuffer strSql = new StringBuffer(); strSql.append("insert into "); strSql.append(c.getSimpleName() + "(" + getModelField(c) + ")"); // strSql.append(c.getSimpleName()); strSql.append(" values "); strSql.append(contentStr(model)); // System.out.println("sql:" + strSql); this.connection(); try { pst = conn.prepareStatement(strSql.toString()); pst.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("sql:" + strSql); } finally { this.close(); } } /** * 通过事物机制删除多个表中的记录,c为表的集合,id为对应要删除的id集合 * * @param c * @param id * @return */ public boolean delete(ArrayList<Class> c, ArrayList<Integer> id) { boolean value = false; Field[] field; StringBuffer strSql = null; this.connection(); try { conn.setAutoCommit(false); Statement cst = conn.createStatement(); for (int i = 0; i < id.size(); i++) { field = c.get(i).getDeclaredFields(); strSql = new StringBuffer(); strSql.append("delete from "); strSql.append(c.get(i).getSimpleName()); strSql.append(" where " + field[0].getName() + "=" + id.get(i)); cst.addBatch(strSql.toString()); } cst.executeBatch(); conn.commit(); value = true; conn.setAutoCommit(true); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { this.close(); } return value; } /** * 通过反射删除一条记录 * * @param c * @param id */ public void delete(Class c, int id) { Field[] field = c.getDeclaredFields(); StringBuffer strSql = new StringBuffer(); strSql.append("delete from "); strSql.append(c.getSimpleName()); strSql.append(" where " + field[0].getName() + "=" + id); try { this.connection(); pst = conn.prepareStatement(strSql.toString()); pst.executeUpdate(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); System.out.println("error sql:" + strSql); } finally { this.close(); } } /** * 通过反射获得最大值id * * @param c * @return */ public int getMaxID(Class c) { int value = 0; Field[] field = c.getDeclaredFields(); StringBuffer strSql = new StringBuffer(); strSql .append("select max(" + field[0].getName() + ")+1 as maxid from "); strSql.append(c.getSimpleName()); try { this.connection(); pst = conn.prepareStatement(strSql.toString()); rs = pst.executeQuery(); rs.next(); value = rs.getInt("maxid"); if (value == 0) { value = 1; } } catch (Exception e) { // TODO: handle exception } finally { this.close(); } return value; } /** * 将返回的一行记录按顺序保存到ArrayList中 * * @param c * @param id * @return */ public <T> T getModel(Class<T> c, int id) { T t = null; String strFieldName = ""; ArrayList<T> list = new ArrayList(); Field[] field = c.getDeclaredFields(); StringBuffer strSql = new StringBuffer(); strSql.append("select "); strSql.append(getModelField(c)); strSql.append(" from "); strSql.append(c.getSimpleName()); strSql.append(" where " + field[0].getName() + "=" + id); System.out.println(strSql); Method method = null; try { this.connection(); pst = conn.prepareStatement(strSql.toString()); rs = pst.executeQuery(); while (rs.next()) { t = c.newInstance(); for (int i = 0; i < field.length; i++) { strFieldName = setModelFieldName(field[i].getName()); method = c.getMethod(strFieldName, field[i].getType()); // if (rs.getObject(i + 1).getClass().getName().equals( // "java.sql.Timestamp")||rs.getObject(i + // 1).getClass().getName().equals( // "java.sql.Date")) { // method.invoke(t, rs.getObject(i + 1).toString()); // } else { method.invoke(t, rs.getObject(i + 1)); // } } list.add(t); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } finally { this.close(); } return list.get(0); } /** * 返回查询结果 * * @param <T> * @param c * @param strWhere * @return */ public <T> ArrayList<T> getModelList(Class<T> c, String strWhere) { String strFieldName = ""; ArrayList<T> list = new ArrayList<T>(); T t = null; StringBuffer strSql = new StringBuffer(); strSql.append("select "); strSql.append(getModelField(c)); strSql.append(" from "); strSql.append(c.getSimpleName()); if (!strWhere.equals("")) { strSql.append(" where " + strWhere); } // System.out.println(strSql); Field[] field = c.getDeclaredFields(); Method method = null; try { this.connection(); pst = conn.prepareStatement(strSql.toString()); rs = pst.executeQuery(); while (rs.next()) { t = c.newInstance(); for (int i = 0; i < field.length; i++) { strFieldName = setModelFieldName(field[i].getName()); method = c.getMethod(strFieldName, field[i].getType()); // if (rs.getObject(i + 1).getClass().getName().equals( // "java.sql.Timestamp")||rs.getObject(i + // 1).getClass().getName().equals( // "java.sql.Date")) { // method.invoke(t, rs.getObject(i + 1).toString()); // } else { method.invoke(t, rs.getObject(i + 1)); // } // System.out.println("111"); } list.add(t); /* * method获得 */ } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return list; } /** * 返回查询结果,返回类型为二维数组 * * @param <T> * @param c * @param strWhere * @return */ public <T> Object[][] getModelListToArray(Class<T> c, String strWhere) { ArrayList<T> model = this.getModelList(c, strWhere); // System.out.println(model); Object o = null; String fieldmethod = ""; Method method = null; Field[] field = c.getDeclaredFields(); Object data[][] = new Object[model.size()][field.length]; Class modelclass = null; for (int j = 0; j < model.size(); j++) { modelclass = model.get(j).getClass(); // System.out.println(modelclass); // try { // // o=(T)modelclass.newInstance(); // } catch (InstantiationException e1) { // // TODO Auto-generated catch block // e1.printStackTrace(); // } catch (IllegalAccessException e1) { // // TODO Auto-generated catch block // e1.printStackTrace(); // } field = modelclass.getDeclaredFields(); // System.out.println(field.length); for (int i = 0; i < field.length; i++) { fieldmethod = getFieldMethod(field[i].getName()); // System.out.println(fieldmethod); try { method = modelclass.getMethod(fieldmethod, null); data[j][i] = method.invoke(model.get(j), null); } catch (Exception e) { e.printStackTrace(); } } } return data; } public int getLength() { return 0; } /** * 获取相应字段的setMethod * * @param name * @return */ private String setModelFieldName(String str) { // TODO Auto-generated method stub String a = str.substring(0, 1); String b = str.substring(1, str.length()); return ("set" + a.toUpperCase() + b); } /** * public Object getModel(Class c,int id) * * @return */ private String getModelField(Class c) { String value = ""; Field[] field = c.getDeclaredFields(); for (int i = 0; i < field.length - 1; i++) { value += field[i].getName() + ","; } value += field[field.length - 1].getName(); // System.out.println(value); return value; } public Object[] getModelFieldNames(Class c) { String value = ""; value = this.getModelField(c); Object[] str = value.split(","); // System.out.println(value); return str; } /** * values(1,'2',3) * * @param model * @return */ private String contentStr(Object model) { String value = "("; String fieldmethod = "";// Class c = model.getClass(); Field[] field = c.getDeclaredFields(); Method method = null;// try { for (int i = 0; i < field.length - 1; i++) { fieldmethod = getFieldMethod(field[i].getName());// // System.out.println(fieldmethod); method = c.getMethod(fieldmethod, null);// if (!field[i].getType().getSimpleName().equals("Integer")) { // value += "'" + field[i].get(model) + "',"; value += "'" + method.invoke(model, null) + "',"; } else { // value += field[i].get(model) + ","; value += method.invoke(model, null) + ","; } } fieldmethod = getFieldMethod(field[field.length - 1].getName());// method = c.getMethod(fieldmethod, null);// if (field[field.length - 1].getType().getSimpleName().equals( "String")) { // value += "'" + field[field.length - 1].get(model) + "')"; value += "'" + method.invoke(model, null) + "')"; } else { // value += field[field.length - 1].get(model) + ")"; value += method.invoke(model, null) + ")"; } } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return value; } /** * 通过字段得到对应的get方法名 * * @param str * @return */ private String getFieldMethod(String str) { // TODO Auto-generated method stub String a = str.substring(0, 1); String b = str.substring(1, str.length()); return ("get" + a.toUpperCase() + b); } } // /:~
jdbc.bll.DbHelperSql.java
package jdbc.bll; import java.util.ArrayList; /** * 业务逻辑层 * * @author XudongChen * */ public class DbHelperSql{ private jdbc.dal.DbHelperSql dal = null; public DbHelperSql() { init(); } /** * 初始化 */ private void init() { // TODO Auto-generated method stub dal = new jdbc.dal.DbHelperSql();// 数据操作初始化 } /** * 根据id判断该条记录是否存在 * @param c * @param id * @return */ public boolean isExist(Class c,int id) { return dal.isExist(c, id); } /** * 事务机制和反射机制的多表增加操作 * @param c 数据库的表集合 * @param model 数据model * @param sqllist 其他还需要执行的sql语句 * @return 操作结果状态(true,false) */ public boolean add(ArrayList<Class> c, ArrayList<Object> model,ArrayList<String> sqllist) { return dal.add(c, model, sqllist); } /** * 事务机制添加数据 * @param c * @param model */ public boolean add(ArrayList<Class> c, ArrayList<Object> model) { return dal.add(c, model); } /** * 增加一条记录 * @param c * @param model */ public void add(Class c,Object model) { dal.add(c,model); } /** * 通过事务机制和反射机制,删除对应表中的数据 * @param c 表集合 * @param id 主键集合 * @return 操作结果,true,false */ public boolean delete(ArrayList<Class> c, ArrayList<Integer> id) { return dal.delete(c, id); } /** * 删除一条记录 * @param c * @param id */ public void delete(Class c,int id) { dal.delete(c, id); } /** * 返回表中的最大值 * @param c * @return */ public int getMaxID(Class c) { return dal.getMaxID(c); } /** * 根据主键得到一条记录 * @param <T> * @param c * @param id * @return */ public <T> T getModel(Class<T> c,int id) { return (T) dal.getModel(c, id); } /** * 更新一条记录 * @param c * @param model * @return */ public boolean update(Class c,Object model) { return dal.update(c, model); } /** * 通过反射获得查询结果 * @param <T> * @param c * @param strWhere * @return */ public <T> ArrayList<T> getModelList(Class<T> c, String strWhere) { return dal.getModelList(c, strWhere); } /** * 返回查询结果,返回类型为二维数组 * @param <T> * @param c * @param strWhere * @return */ public <T> Object[][] getModelListToArray(Class<T> c, String strWhere) { return dal.getModelListToArray(c, strWhere); } /** * 返回查询结果,返回类型为一维数组 * @param c * @return */ public Object[] getModelFieldNames(Class c) { return dal.getModelFieldNames(c); } } ///:~