<?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();
}