項目中老是遇到數據庫異常關閉的情況,真煩,
想用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;
}
}
}