Java DatabaseMetaData.getSchemas()返回空的ResultSet,预期的非空ResultSet
作者:互联网
试图了解这里发生了什么. DatabaseMetaData返回一个空结果集,而实际上相同的SQL查询却没有.这不是主要问题,因为我正在使用第二个代码示例来解决.
DatabaseMetaData dmd = this.connection.getMetaData();
ResultSet rs = dmd.getSchemas();
while (rs.next()){
// empty result set
}
预期为非空结果集.
ResultSet rs = this.connection.prepareStatement("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA;").executeQuery();
while (rs.next()){
// non-empty result set with expected results
}
期望得到一个非空的结果集.
解决方法:
据我所知,MySQL JDBC驱动程序考虑的是目录,而不是模式.因此,您应该改用getCatalogs
(在所有使用它的地方,都需要使用catalog参数,而不是schema参数).
getSchemas
method in Connector/J始终返回空结果集:
public java.sql.ResultSet getSchemas() throws SQLException {
Field[] fields = new Field[2];
fields[0] = new Field("", "TABLE_SCHEM", java.sql.Types.CHAR, 0);
fields[1] = new Field("", "TABLE_CATALOG", java.sql.Types.CHAR, 0);
ArrayList<ResultSetRow> tuples = new ArrayList<ResultSetRow>();
java.sql.ResultSet results = buildResultSet(fields, tuples);
return results;
}
getCatalogs
返回SHOW DATABASES的结果.在DatabaseMetaDataUsingInfoSchema
中,您看到信息模式的TABLE_SCHEMA列别名为TABLE_CAT(对于目录),并且在查询中将catalog参数作为TABLE_SCHEMA列的值传递:
String sql = "SELECT TABLE_SCHEMA AS TABLE_CAT, NULL AS TABLE_SCHEM, TABLE_NAME,"
+ "COLUMN_NAME, NULL AS GRANTOR, GRANTEE, PRIVILEGE_TYPE AS PRIVILEGE, IS_GRANTABLE FROM INFORMATION_SCHEMA.COLUMN_PRIVILEGES WHERE "
+ "TABLE_SCHEMA LIKE ? AND TABLE_NAME =? AND COLUMN_NAME LIKE ? ORDER BY COLUMN_NAME, PRIVILEGE_TYPE";
java.sql.PreparedStatement pStmt = null;
try {
pStmt = prepareMetaDataSafeStatement(sql);
if (catalog != null) {
pStmt.setString(1, catalog);
} else {
pStmt.setString(1, "%");
}
pStmt.setString(2, table);
pStmt.setString(3, columnNamePattern);
标签:jdbc,database-metadata,java,mysql 来源: https://codeday.me/bug/20191120/2042361.html