<?php
class DbHelper
{
private $DbConnectionString;
private $Username;
private $Password;
public function __construct($dbConnectionString,$username,$password) {
$this->DbConnectionString = $dbConnectionString;
$this->Username = $username;
$this->Password = $password;
}
public function GetPDO()
{
return new PDO($this->DbConnectionString, $this->Username, $this->Password);
}
public function GetData($sql)
{
$pdo = $this->GetPDO();
return $pdo->query($sql)->fetchAll();
}
public function GetLine($sql)
{
$result = $this->GetData($sql);
if($result)
{
return $result[0];
}else{
return NULL;
}
}
public function GetVar($sql)
{
$result = $this->GetLine($sql);
if($result)
{
return $result[0];
}else{
return NULL;
}
}
public function RunSQL($sql)
{
$pdo = $this->GetPDO();
$pdo->exec($sql);
}
}
?>
使用演示:
<?php
include 'DbHelper.class.php';
try {
header("Content-Type: text/html; charset=utf-8");
$db = new DbHelper("sqlsrv:Server=.,1433;Database=MOV", "sa", "sa");
$c = $db->GetVar("select count(*) from MMovie");
print $c;
$db->RunSQL("delete from MMovie where id in(select top 1 id from MMovie)");
print "<br />";
$c = $db->GetVar("select count(*) from MMovie");
print $c;
} catch (PDOException $e){
print "Error: " . $e->getMessage() . "<br/>";
die();
}
本文通过实例展示了如何使用PHP构建数据库助手类,实现数据库连接、查询、数据获取等功能,并详细介绍了错误处理机制,包括捕获并显示PDO异常。

1016

被折叠的 条评论
为什么被折叠?



