< 上一课 | 下一课 >

结果集

您可以遍历由查询返回的 ResultSet,以检索结果集所包含的每条记录的数据。

以下是使用 ResultSet 对象时要执行的步骤:

  1. 创建 ResultSet 对象。 要创建 ResultSet 对象,可使用 Session 对象的 BuildResultSetBuildSQLQuery 方法。这两个方法都返回一个 ResultSet 对象,该对象可用于运行查询,但不包含任何数据。
  2. 运行查询以使用数据填充 ResultSet。 要运行查询,需要调用 ResultSet 对象的 ExecuteExecuteAndCountRecords 方法。这些方法使用数据库中的数据填充 ResultSet。
  3. 浏览产生的数据,直至找到所需的记录。 要移至结果集中的第一条记录,请调用 MoveNext 方法,该方法将初始化游标并将其移至第一条记录。然后,您可以使用 ResultSet 的方法获取有关第一条记录的字段的信息。要移至后续记录,可再次使用 MoveNext 方法。 接着,您可以使用 ResultSet 的方法获取有关当前记录的字段的信息。
  4. 从记录的字段中检索值。 使用 ResultSet 对象的方法获取有关记录的字段的信息。

示例

以下代码示例演示如何使用 ResultSet 对象的方法遍历由查询返回的数据:

use CQPerlExt; 
#Start a Rational ClearQuest session 
$SessionObj = CQSession::Build(); 
$dbsetname = "CQMS.SAMPL.HOME"; 

#Refresh list of accessible databases 
$databases = $SessionObj->GetAccessibleDatabases("MASTR", "", $dbsetname); 

#Log into a database 
$SessionObj->UserLogon("admin","","SAMPL",$dbsetname); 

#Create a Query by calling the BuildQuery(record_type) method, You specify a record type as the argument
$querydef = $SessionObj->BuildQuery("defect"); 
#  You use the BuildField (field_name) method for each field value that you want included for each record 
#  returned in the result set for the query:
$querydef->BuildField("id"); 
$querydef->BuildField("headline"); 
$querydef->BuildField("owner.login_name"); 
$querydef->BuildField("submit_date"); 

# The BuildResultSet(query_def_name) you build will contain the records returned by the query: 
$resultset = $SessionObj->BuildResultSet($querydef); 

# The following command runs the query and counts the number of records in the result set.
$ct = $resultset->ExecuteAndCountRecords(); 

for ($i = 0; $i < $ct; $i++) { 
#  You use the MoveNext method to iterate through the records in the ResultSet:
$resultset->MoveNext(); 
# You can also loop through ResultSet without using the count, like this:
# while ( $resultset->MoveNext == $CQPerlExt::CQ_SUCCESS ) {

#  You use the GetColumnValue(column_number) method to get the field values that you specified to be returned 
# for each record (by calling the BuildField method for each field to include):
   print $resultset->GetColumnValue(1); 
   print " "; 
   print $resultset->GetColumnValue(2); 
   print " "; 
   print $resultset->GetColumnValue(3); 
   print " "; 
   print $resultset->GetColumnValue(4); 
   print "\n"; 
   } 

# There are also methods to discover column properties such as these methods: 
# ResultSet:GetNumberOfColumns 
# ResultSet:GetColumnType (all values are returned as strings, but you may wish to format them) 
#ResultSet:GetColumnLabel

CQSession::Unbuild($SessionObj); 
大多数有用的查询都包含您定义的过滤器,用于检索符合某些条件的特定记录。下一课将介绍如何定义搜索条件。
< 上一课 | 下一课 >

反馈