本地代码
//获取表所有字段
private List<String> getFieldListFromConnectMetaData(@NonNull DatabaseConnectModel model, String tableName) {
try {
Class.forName(model.getDriverClassName());
Connection connection = DriverManager.getConnection(model.getUrl(),
model.getUsername(), model.getPassword());
ResultSet rs = connection.getMetaData().getColumns(null, null, tableName, null);
List<String> fieldNameList = Lists.newArrayList();
while (rs.next()) {
fieldNameList.add(rs.getString("COLUMN_NAME"));
}
return fieldNameList;
} catch (ClassNotFoundException | SQLException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
//获取库所有表
private List<String> getTableListFromConnectMetaData(@NonNull DatabaseConnectModel model) {
try {
Class.forName(model.getDriverClassName());
Connection connection = DriverManager.getConnection(model.getUrl(),
model.getUsername(), model.getPassword());
ResultSet rs = connection.getMetaData().getTables(null, null, "%", new String[]{});
List<String> tableNameList = Lists.newArrayList();
while (rs.next()) {
tableNameList.add(rs.getString("TABLE_NAME"));
}
return tableNameList;
} catch (ClassNotFoundException | SQLException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
返回的字段列和表都是重复的
DatabaseMetaData .getTables() 方法常常用来获取数据库中的所有表信息。 但我想要获取我的本地数据库db_test 中的表信息,出现了错误。
解决方案
??mysql8.0的驱动,在5.5之前nullCatalogMeansCurrent 属性默认为true ,8.0中默认为false ,官网链接地址。所以导致DatabaseMetaData.getTables() 加载了全部的无关表。
??解决方法是,在jdbc 创建连接的url后加上&nullCatalogMeansCurrent=true
|