4.2 查询
假设与数据库已经连接就绪 , 下面我们就来实际的应用对数据库的查询 。下面的代码演示了一个连接并查询的典型例子:
/*
* 连接数据库并执行查询
*/
function printoraerr($in_cur)
{
// 检查Oracle是否出错
// 如果存在错误则显示
// 当指针被激活时每次请求Oracle后调用该函数
if(ora_errorcode($in_cur))
echo "Oracle code - ".ora_error($in_cur)."\n";
return;
}
/** 主程序 */
if (!($conn=ora_logon("user@TNSNAME","password")))
{
echo "Connection to database failed\n";
exit;
}
echo "Connected as connection - $conn
\n";
echo "Opening cursor ...
\n";
$cursor=ora_open($conn); printoraerr($cursor);
echo "Opened cursor - $cursor
\n";
$qry="select user,sysdate from dual";
echo "Parsing the query $qry ...
\n";
ora_parse($cursor,$qry,0); printoraerr($cursor);
echo "Query parsed
\n";
echo "Executing cursor ...
\n";
ora_exec($cursor); printoraerr($cursor);
echo "Executed cursor
\n";
echo "Fetching cursor ...
\n";
while(ora_fetch($cursor))
{
$user=ora_getcolumn($cursor,0); printoraerr($cursor);
$sysdate=ora_getcolumn($cursor,1); printoraerr($cursor);
echo " row = $user, $sysdate
\n";
}
echo "Fetched all records
\n";
echo "Closing cursor ...
\n";
ora_close($cursor);
echo "Closed cursor
\n";
echo "Logging off from oracle...
\n";
ora_logoff($conn);
echo "Logged off from oracle
\n";
?
(译者注:以上代码段缺少注释,请读者参考PHP Manual的Oracle数据库函数部分)
4.3 显示结果
以下代码演示了怎样查询数据库并将结果输出:
function printoraerr($in_cur, $conn)
{
// 检查Oracle是否出错
// 如果存在错误则显示
// 当指针被激活时每次请求Oracle后调用该函数
// If it encountered an error, we exit immediately
if(ora_errorcode($in_cur))
{
echo "Oracle code - ".ora_error($in_cur)."
n";
ora_logoff($conn);
exit;
}
return;
}
function exequery($w_qry,$conn)
{
$cursor=ora_open($conn); printoraerr($cursor,$conn);
ora_parse($cursor,$w_qry,0); printoraerr($cursor,$conn);
ora_exec($cursor); printoraerr($cursor,$conn);
$numrows=0;
$w_numcols=ora_numcols($cursor);
// 显示头部
echo "
\n";
for ($i=0;$i$w_numcols;$i++)
{
$align=(ora_columntype($cursor,$i)=="NUMBER")?"RIGHT":"LEFT";
echo "\t ".ora_columnname($cursor,$i)." \n";
}
echo "
\n";
while(ora_fetch($cursor))
{
echo " \n";
for ($i=0;$i$w_numcols;$i++)
{
$align=(ora_columntype($cursor,$i)=="NUMBER")?"RIGHT":"LEFT";
if(ora_columntype($cursor,$i)=="LONG")
echo " ".
ora_getcolumn($cursor,$i)."
\n";
else
echo " ".ora_getcolumn($cursor,$i)." \n";
printoraerr($cursor,$conn);
}
$numrows++;
echo "
\n";
}
if ($numrows==0)
echo " Query returned no records
\n";
else
{
echo " \n";
echo " Count \n";
echo " $numrows \n";
echo "
\n";
}
echo " \n";
ora_close($cursor);
return;
}
// 主程序
if(!($conn=ora_logon("user@SID","password")))
{
echo "Error: Cannot connect to database\n";
exit;
}
$qry="SELECT
deptno \"Dept\"
,empno \"Emp\"
,empnm \"Name\"
,salary \"Salary\"
FROM
employee
ORDER BY 1,2";
exequery($qry);
ora_logoff($conn);
?
(译者注:以上代码段缺少注释,请读者参考PHP Manual的Oracle数据库函数部分)
推荐阅读
- 苹果笔记本电脑怎么设置,苹果笔记本电脑怎么设置不黑屏休眠
- oracle数据量大排序好久,oracle排序性能优化
- 高效的数据库管理器mysql,mysql数据库管理工具
- 摸摸鱼体育竞技类游戏,摸摸鱼游戏分享
- c语言用文件函数调用函数 c语言中如何调用文件中的数据
- 新媒体如何写观点分析范文,对新媒体的观点
- 技嘉1660显卡怎么样,技嘉显卡1660 6g怎么样
- 减少退单的直播话术,直播退货率很高
- 哪些大厂在用go语言 go语言用的多吗