我正在将PHP应用程序从MySQL转换为DB2,IBM_DB2和MySQL PHP扩展之间似乎有一些我无法理解或解决的差异。
如果我在包含 db2_connect()
和 db2_exec()
的函数之外调用记录集,db2_fetch_array()
似乎无法从记录集中返回一行,即使返回的记录集存储为对象属性并且在以后调用时仍返回资源 ID 号。
任何人都可以看到为什么对下面的getNextRow()
方法的调用无法返回记录集中的下一行吗? 这在MySQL中工作正常。
class TestClass
{
//Properties
public $result; //Holds the record set returned from a query
public $sql; //Holds the value of the last sql query sent
function goQuery($sql)
{
$this->sql = $sql;
if($con = db2_connect("MASTER", "DB2USER", "DB2PASSWORD"))
{
echo "<li>Connected to master database</li>";
}
if($this->result = db2_exec($con, $sql))
{
echo "<li>SQL Query ran successfully</li>";
}
//Just proving some data can be returned as this point
$row = db2_fetch_assoc($this->result);
if(sizeof($row) > 0)
{
echo "<li>db2_fetch_assoc returned a record in the resultset (Resource ID: " . $this->result . ") that has " . sizeof($row) . " fields</li>";
}
//Just proving some data can be returned as this point
$row = $this->getNextRow();
if(sizeof($row) > 0)
{
echo "<li>getNextRow() returned a record in the resultset (Resource ID: " . $this->result . ") the has " . sizeof($row) . " fields</li>";
}
}
function getNextRow()
{
if($row = db2_fetch_assoc($this->result))
{
return $row;
}
else
{
echo "<li>No results found in " . $this->result . "</li>";
}
}
}
$q = new TestClass();
echo "<h2>Running query TestClass->goQuery()</h2>";
echo "<ul>";
$q->goQuery("SELECT * FROM users");
echo "</ul>";
echo "<h2>Trying to fetch a result using TestClass->getNextRow()</h2>";
echo "<ul>";
$row = $q->getNextRow();
echo "</ul>";
这当前会产生以下输出:
Running query TestClass->goQuery()
Connected to master database
SQL Query ran successfully
db2_fetch_assoc returned a record in the resultset (Resource ID: Resource id #12) that has 25 fields
getNextRow() returned a record in the resultset (Resource ID: Resource id #12) the has 25 fields
Trying to fetch a result using TestClass->getNextRow()
No results found in Resource id #12
我能够通过使用持久连接来解决:
$con = db2_pconnect("MASTER", "USER", "PASSWORD")
看起来 DB2 连接和所有返回的资源在调用它们的函数结束时停止存在 - 除非使用持久连接。
这是 DB2 独有的,因为我发现在 MySQL 中实现这一点不需要持久连接。