上一篇文章讲到了用Sql语句取得表空间,表空间下的表,表的字段信息的方法,但是我们还有更加通用的方法,那就是用Jdbc API直接操作,请看下面三个函数.
/**
* 取得数据库中所有Schema
*
* @return
*/
public List getTableSchemas(){
List retval = new ArrayList();
try {
Connection connection = getConnection();
DatabaseMetaData dbmd = connection.getMetaData();
ResultSet resultSet = dbmd.getSchemas();
while (resultSet.next()) {
String tableName = resultSet.getString(1);
retval.add(tableName);
}
} catch (SQLException e) {
e.printStackTrace();
}
return retval;
}
/**
* 取得某Schema下所有表名
*
* @param schema
* @return
*/
public List getTablesInSchema(String schema){
List retval = new ArrayList();
try {
Connection connection = getConnection();
DatabaseMetaData dbmd = connection.getMetaData();
String[] types = { "TABLE" };
ResultSet resultSet = dbmd.getTables(null, null, "%", types);
// Get the table names
while (resultSet.next()) {
// Get the table name
String tableName = resultSet.getString(3);
String tableSchema = resultSet.getString(2);
if (tableSchema.equals(schema)) {
retval.add(tableName);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return retval;
}
/**
* 取得某表下的所有字段信息
*
* @param table
* @return
*/
public List getColumnInfoesInTable(String table){
List retval = new ArrayList();
try {
Connection connection = getConnection();
// Create a result set
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM " + table);
// Get result set meta data
ResultSetMetaData rsmd = rs.getMetaData();
int numColumns = rsmd.getColumnCount();
// Get the column names; column indices start from 1
for (int i = 1; i < numColumns + 1; i++) {
ColumnInfoBean columnInfoBean = new ColumnInfoBean();
// 字段名
columnInfoBean.setName(rsmd.getColumnName(i));
// 字段类型
columnInfoBean.setTypeName(rsmd.getColumnTypeName(i));
// 字段类型对应的java类名
columnInfoBean.setClassName(rsmd.getColumnClassName(i));
// 显示的长度
columnInfoBean.setDisplaySize(String.valueOf(rsmd
.getColumnDisplaySize(i)));
// Precision
columnInfoBean.setPrecision(String
.valueOf(rsmd.getPrecision(i)));
// Scale
columnInfoBean.setScale(String.valueOf(rsmd.getScale(i)));
retval.add(columnInfoBean);
}
} catch (SQLException e) {
e.printStackTrace();
}
return retval;
}
