iBatis应用之获取表的元数据

iBatis是一种半ORM,为程序员提供了较大的灵活性,今天就展示一在iBatis中获取表元数据的例子,
所谓表的元数据就就是关于表的数据的数据,在一个特殊的应用场合需要查出了指定SQL中包含的字段的信息,
包括:字段类型和长度定义,
我这里的sqlMapClient是由Spring注入的。

  public void ShowFieldType(String sql) throws Exception{
DataSource dataSource = this.sqlMapClient.getDataSource();
Connection con = dataSource.getConnection();
Statement stmt = null;
ResultSet rs = null;
try {
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
ResultSetMetaData rsMetaData = rs.getMetaData();
int columnCount = rsMetaData.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
logger.info("field Name:"+ rsMetaData.getColumnName(i)+
   " field Type:"+rsMetaData.getColumnTypeName(i)+
" size:"+rsMetaData.getColumnDisplaySize(i));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
rs.close();
stmt.close();
con.close();
}
}
测试类:
ITestDBDao dao = (ITestDBDao)SystemBeans.getBean("testdbDaoDean");
//给定一个SQL,为了提高效率不查数据,因此使用了一个where 1=2条件
dao.ShowFieldType("select * from ices_cc_data where 1=2");

运行结果:
 INFO [main] [2011-09-04 15:57:18] field Name:ID field Type:INTEGER size:11
 INFO [main] [2011-09-04 15:57:18] field Name:NE_NAME field Type:VARCHAR size:30
 INFO [main] [2011-09-04 15:57:18] field Name:CYCLE field Type:BIGINT UNSIGNED size:20
 INFO [main] [2011-09-04 15:57:18] field Name:CC_ID field Type:INTEGER size:11
 INFO [main] [2011-09-04 15:57:18] field Name:CALL_PHASE field Type:INTEGER size:11
 INFO [main] [2011-09-04 15:57:18] field Name:CC_TOTAL_VALUE field Type:INTEGER size:11
 INFO [main] [2011-09-04 15:57:18] field Name:CC_VALUE field Type:INTEGER size:11

运行结果中列出了ices_cc_data表的所有字段名和字段长度
其实 SqlMapClient提供了getCurrentConnection()方法,但是测试发现,该方法返回的结果为null,这一点很奇怪,
所以只好返回DataSource()然后再获取一个Connection()

你可能感兴趣的:(java,ibatis,元数据)