(學習記錄)
代碼中Table類與Field類請參照:http://meijia.blog.51cto.com/8684191/1563874
可參考api調整相關參數。
(同樣注意格式)
1. 方法如下
public List<Table> export() {
List<Table> tableList = new ArrayList<Table>();
Connection conn = DBUtil.getConnection();
ResultSet tableRs = null; // 存庫元數據
ResultSet colRs = null;//存儲表元數據
try {
DatabaseMetaData dbmd = conn.getMetaData();//返回連接到的數據庫此 Connection 對象所連接的數據庫的元數據
//獲取所有表
List<String> tableNameList = new ArrayList<String>();
tableRs = dbmd.getTables(null, "%", "%", new String[]{"TABLE"}); //所有表
while (tableRs.next()) {
String tableName = tableRs.getString("TABLE_NAME");//表名
tableNameList.add(tableName);
}
List<Field> fieldList = null;//存儲每一個表的所有字段
Table table = null;
for (String name : tableNameList ) {
table = new Table();
//獲取表的字段
colRs = dbmd.getColumns(null, "%", name, "%");//當前表的字段
Field field = null;
fieldList = new ArrayList<Field>();
while (colRs.next()) {
field = new Field();
String columnName = colRs.getString("COLUMN_NAME");//名稱
String columnType = colRs.getString("TYPE_NAME");//類型
int datasize = colRs.getInt("COLUMN_SIZE");//字段長度
int digits = colRs.getInt("DECIMAL_DIGITS");
int nullable = colRs.getInt("NULLABLE");//返回1就表示可以是Null,而0就表示Not Null
field.setColumnName(columnName);
field.setTypeName(columnType);
field.setColumnSize(datasize);
field.setDecimal_digits(digits);
field.setNullable(nullable);
fieldList.add(field);
}
table.setTableName(name);
table.setField(fieldList);
tableList.add(table);
}
} catch (SQLException ex) {
Logger.getLogger(ExportOracleTable.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if(colRs != null) {
try {
colRs.close();
} catch (SQLException ex) {
Logger.getLogger(ExportOracleTable.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(tableRs != null) {
try {
tableRs.close();
} catch (SQLException ex) {
Logger.getLogger(ExportOracleTable.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(conn != null) {
try {
conn.close();
} catch (SQLException ex) {
Logger.getLogger(ExportOracleTable.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return tableList;
}