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()