在几天前遇到这个具体问题后,我终于想出了一个可以完成这项工作的解决方案。当然,它既不漂亮也不......好吧......任何东西,但它有效。
基本上,我根据 ResultSet 中的列检查数据库中的每个表。
我希望其他人可以使用它。我花了大约一天的时间才弄清楚这一点。
注意:我使用的是 CachedRowSet 而不是 ResultSet,这不需要我一直保持数据库连接打开。
private static String getTableNameByCols(ResultSetMetaData rsmd, DatabaseMetaData dbmd) throws SQLException{
String errorString = "No matching table found for the given column Set";
String ret = null, origColName, origDatatype, tableName;
String[] names = {"TABLE"};
ResultSet tables = dbmd.getTables(null, username, "%", names);
// get all the columns out of the rsmd and put them into an Array
Integer numberOfColumns = rsmd.getColumnCount();
String[] origColNames = new String[numberOfColumns+1];
String[] origColTypeNames = new String[numberOfColumns+1];
for (int i=1; i<numberOfColumns+1; i++){
origColNames[i] = rsmd.getColumnName(i);
origColTypeNames[i] = rsmd.getColumnTypeName(i);
}
ResultSet columns = null;
while (tables.next()) {
tableName = tables.getString("TABLE_NAME");
columns = dbmd.getColumns(null, null, tableName, null);
CachedRowSet crs = new CachedRowSetImpl();
crs.populate(columns);
Integer tablesNumberOfColumns = crs.size();
int i = 1;
if (numberOfColumns.intValue() == tablesNumberOfColumns.intValue()){
while (crs.next()) {
origColName = origColNames[i];
origDatatype = origColTypeNames[i];
String colName = crs.getString(4);
String datatype = crs.getString(6);
//int datasize = columns.getInt("COLUMN_SIZE");
//int nullable = columns.getInt("NULLABLE");
if (origColName.equals(colName) && origDatatype.equals(datatype) ){
ret = tableName;
} else {
ret = null;
}
i += 1;
} // looked at all the columns
crs.close();
}// same # of columns check over
if (ret != null) {
break;
}
columns.close();
}
verify(ret, errorString);
return ret;
}
环绕方法:
private static boolean updateLocalTable(ResultSet rs){
ResultSetMetaData rsmd;
DatabaseMetaData dbmd;
String table_name;
boolean ret = false;
try {
rsmd = rs.getMetaData();
dbmd = conn.getMetaData();
table_name = getTableNameByCols(rsmd, dbmd);
/* ... do stuff with it ... */
} catch (Exception e) {
print("kablooey! \n" + e.getStackTrace());
}
return ret;
}