查詢mysql資料表 獲得表詳細資訊
阿新 • • 發佈:2019-01-28
public static void main(String[] args) throws Exception {
Connection connection = DBConnectionUtil.getConnection();
BaseDao baseDao = new BaseDao(connection);
String DBName = "fwdb";
ResultSet resultSet1 = baseDao.getRes("select TABLE_NAME from TABLES where TABLE_SCHEMA = '" +DBName+"'");
//遍歷該資料的所有表
while (resultSet1.next()) {
String table_name = resultSet1.getString(1);
//獲得該表的詳細資訊
List<TableInfo> infos = getColumnInfo(baseDao,table_name);
int i=0;
System.out.println("===============================" );
//遍歷表的詳細資訊
for (TableInfo table : infos) {
if(i==0){
System.out.println("表名稱: " + table.getTableName());
i++;
}
System.out.println(
" " + table.getColumnName()
+ " " + table.getDataType()
+ " " + table.getCharacterMaximumLength()
+ " " + table.getColumnComment());
}
System.out.println("===============================");
}
//關閉連線
baseDao.closeAll(resultSet1, null, connection);
}
/**
*
* @param baseDao
* @param tableName
* @return 獲得給表的詳細資訊
* @throws Exception
*/
private static List<TableInfo> getColumnInfo(BaseDao baseDao,String tableName) throws Exception {
ResultSet resultSet = baseDao
.getRes("select ABLE_NAME,COLUMN_NAME,DATA_TYPE,CHARACTER_MAXIMUM_LENGTH,COLUMN_TYPE,COLUMN_COMMENT from COLUMNS where TABLE_NAME = '" + tableName + "'");
List<TableInfo> tableInfos = new ArrayList<TableInfo>();
// 獲得給表的詳細資訊新增到 List中
while (resultSet.next()) {
TableInfo table = new TableInfo();
String columnName = resultSet.getString(2);
String dataType = resultSet.getString(3);
String characterMaximumLength = resultSet.getString(4);
String columnComment = resultSet.getString(6);
table.setTableName(tableName);
table.setColumnName(columnName);
table.setDataType(dataType);
table.setCharacterMaximumLength(characterMaximumLength);
table.setColumnComment(columnComment);
tableInfos.add(table);
}
return tableInfos;
}