为了在Sybase ASE中查询数据库元数据,我发现这个相关的答案(不是接受的答案)是理想的:
From a Sybase Database, how I can get table description ( field names and types)?
不幸的是,我似乎无法找到任何文档,我应该如何从JDBC调用sp_help
。根据{{3}},sp_help
返回多个游标/结果集。第一个包含有关表本身的信息,第二个包含有关列的信息等。当我这样做时:
PreparedStatement stmt = getConnection().prepareStatement("sp_help 't_language'");
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getObject(1));
// ...
}
我只从第一个光标得到结果。如何访问其他的?
答案 0 :(得分:2)
如果有多个结果集,则需要使用execute()方法而不是executeQuery()。 Here's an example:
CallableStatement cstmt;
ResultSet rs;
int i;
String s;
...
cstmt.execute(); // Call the stored procedure 1
rs = cstmt.getResultSet(); // Get the first result set 2
while (rs.next()) { // Position the cursor 3
i = rs.getInt(1); // Retrieve current result set value
System.out.println("Value from first result set = " + i);
// Print the value
}
cstmt.getMoreResults(); // Point to the second result set 4a
// and close the first result set
rs = cstmt.getResultSet(); // Get the second result set 4b
while (rs.next()) { // Position the cursor 4c
s = rs.getString(1); // Retrieve current result set value
System.out.println("Value from second result set = " + s);
// Print the value
}
rs.close(); // Close the result set
cstmt.close(); // Close the statement
答案 1 :(得分:1)
您还需要调用getUpdateCount()以及getMoreResults()来读取整个结果集。以下是我用来调用sp_helpartition来从SYBASE DB中检索分区信息的一些代码。
try {
connection = getPooledConnection(poolName);
statement = connection.createStatement();
CallableStatement callable = connection.prepareCall(
"{ call sp_helpartition(?) }");
callable.setString(1,tableName);
callable.execute();
int partitions = 0;
/*
* Loop through results until there are no more result sets or
* or update counts to read. The number of partitions is recorded
* in the number of rows in the second result set.
*/
for (int index = 0 ; ; index ++){
if (callable.getMoreResults()){
ResultSet results = callable.getResultSet();
int count = 0 ;
while (results.next()){
count++;
}
if (index == 1){
partitions = count;
}
} else if (callable.getUpdateCount() == -1){
break ;
}
}
return partitions ;
} catch (Exception e) {
return 0 ;
} finally {
statement.close();
connection.close();
}
答案 2 :(得分:0)
感谢Martin Clayton's answer here,我可以弄清楚如何一般地查询Sybase ASE的sp_help
函数。我在blog here中记录了一些关于如何做到这一点的详细信息。我将多个JDBC结果集的支持工作到jOOQ。在sp_help
的情况下,使用jOOQ API调用该函数可能如下所示:
Factory create = new ASEFactory(connection);
// Get a list of tables, a list of user types, etc
List<Result<Record>> tables = create.fetchMany("sp_help");
// Get some information about the my_table table, its
// columns, keys, indexes, etc
List<Result<Record>> results = create.fetchMany("sp_help 'my_table'");