jdbc 封装 Object恢复类型或者其他妙招
自己写了个jdbc的工具类.
抽出主要的方法.
//填充preparedstatement 参数
public static PreparedStatement fillStatement(PreparedStatement pstm,
Object[] params) throws
SQLException {
if (pstm == null || params == null || params.length == 0) {
throw new
NullPointerException("params are empty ");
}
for (int i = 0; i < params.length; i++) {
pstm.setObject(i + 1, params[i]);
}
return pstm;
}
//============================
//取元数据信息这个方法会比较慢,后续会改用配置文件的方法来取
public static List getMetaInfoList(String sql, Connection conn,
Object[] params) throws SQLException{
String newSql = "select * from "+sql+" where 1=2";
ResultSet rs = executeQuery(newSql,conn,params);
ResultSetMetaData rsmd = rs.getMetaData();
int count = rsmd.getColumnCount();
String[] colNames = new String[count];//可以使用setObject 賦值
String[] colLabels = new String[count];//取值用這個
int[] colSqlTypes = new int[count];//sql types 可以由這個對應到java的 type
for(int i =0 ;i<count;i++){
colNames[i]=rsmd.getColumnClassName(i+1);
colLabels[i]=rsmd.getColumnLabel(i+1);
colSqlTypes[i] = rsmd .getColumnType(i+1);
}
List list = new ArrayList(3);
list.add(0, colNames);
list.add(1,colLabels);
list.add(2, colSqlTypes);
return list;
}
//================================
//格式化获取的 游标 数据
public static Object formatterResultSet(ResultSet rs,List metaInfo) throws SQLException{
if(rs==null||rs.isClosed()){
throw new
IllegalArgumentException("the result is closed or null ,resultset:"+rs);
}
String[] collabels = (String[]) metaInfo.get(1);
int count = collabels.length;
while(rs.next()){
for(int i =0 ;i<count ;i++){
rs.getObject(collabels[i]);
}
}
//.....未完
return null ;
}
public static ResultSet executeQuery(String sql, Connection conn,
Object[] params) throws SQLException {
PreparedStatement pstm = conn.prepareStatement(sql);
pstm = fillStatement(pstm, params);
return pstm.executeQuery();
}
//===========================================================
在写到formatterResultSet方法的时候,我突然在数据类型那里卡住了.
请问下,我这样全部使用Object 来做,会不会降低很多效率.可否有提高效率的做法.
还有我该如何恢复失去的类型信息.
可否有具体的代码可以参考.
太深的代码我还看不懂.
------最佳解决方案--------------------/**
* 访问数据库的基类dao
* @version 2.0
* */
public abstract class CoreDao extends PageDao {
@MatchingBean
public JdbcConfig jdbcConfig;
/**
* 获得数据库连接
* @return Connection
*/
public Co