JAVA中把ResultSet转换成LIST

项目中老是遇到数据库异常关闭的情况,真烦,
想用hibernate呢,那个玩意儿又太笨重,感慨C#和PHP的舒适方便性,模拟TP写了个数据处理层,将就用着先
代码里有很多项目中的东西,不要直接COPY了。。。了解实现方法就行了 /**
* @模拟TP数据操作基类框架
* @author 牛牛 Q 184377367
* @20131218
*/ package Model; import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List; import xqlbsw.DB;
import xqlbsw.DataFactory;
import lib.DBC; public class ModelBase { public String table;
public DBC db = null;
public String where = "";
public String Field = ""; public Boolean Delete() throws Exception { String dbChar = "delete " + this.table + " where " + this.where;
DataFactory.GDO().Update(dbChar);
DataFactory.GDO().free();
return true; } public ModelBase table(String t) {
this.table = t;
return this;
} public ModelBase Field(String s) {
this.Field = s;
return this;
} public ModelBase Where(String s) {
this.where = s;
return this;
} public List Select() throws SQLException { if (this.Field == "") {
this.Field = "*";
}
String dbChar = "select " + this.Field + " from " + this.table;
if (this.where != "") {
dbChar += " where " + this.where + "";
} List list = this.toList(DataFactory.GDO().getCrmResult(dbChar));
DataFactory.GDO().free();
return list; } public List toList(ResultSet rs) {
List list = new ArrayList();
try {
// 获取数据库表结构
ResultSetMetaData meta = rs.getMetaData();
Object obj = null;
String clsName = this.getClass().getName();
String aryClassName[] = clsName.split("\\."); while (rs.next()) {
// 获取formbean实例对象
obj = Class.forName(
"Domain." + aryClassName[(aryClassName.length) - 1])
.newInstance();
// 循环获取指定行的每一列的信息
for (int i = 1; i <= meta.getColumnCount(); i++) {
// 当前列名
String colName = meta.getColumnName(i);
// 将列名第一个字母大写(为什么加+""呢?为了把char类型转换为String类型。replace的参数是String类型。)
colName = colName.replace(colName.charAt(0) + "",
new String(colName.charAt(0) + "").toUpperCase());
// 设置方法名
String methodName = "set" + colName;
// 获取当前位置的值,返回Object类型
Object value = rs.getObject(i);
// 利用反射机制,生成setXX()方法的Method对象并执行该setXX()方法。
Method method = obj.getClass().getMethod(methodName,
value.getClass());
method.invoke(obj, value);
}
list.add(obj);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
return list;
}
} }
上一篇:MyGeneration 数据库驱动为空


下一篇:Java多种方式读文件,追加文件内容,等对文件的各种操作