【问题标题】:Php PDO connection in postgrespostgres中的Php PDO连接
【发布时间】:2018-01-03 15:04:38
【问题描述】:

我有一个 php 脚本,它被 ajax 以 4 秒的间隔一次又一次地调用。

try {
    $conn_p = new PDO("pgsql:host=$db_host;dbname=$db_dbname", $db_user, $db_password);
} catch(PDOException $e) {  
    //$e->getMessage();
}

function abc($id)
{
    global $conn_p;

    $st = "select * from table where id=:id";
    $sqlst=$conn_p->prepare($st);
    $bindParamArray=array("id"=>$id);
    $sqlst->execute($bindParamArray);   
    $row=$sqlst->fetch();   
    return $row;
}

function xyz($no)
{
    global $conn_p; 
    $st= "select * from table2 where no=:no and display='Y'";
    $sqlst=$conn_p->prepare($st);
    $bindParamArray=array(':no' => $no);
    $sqlst->execute($bindParamArray);   
    $row=$sqlst->fetch();   
    return $row;
}

function abc($id)
{
    global $conn_p;

    $st = "select * from table where id=:id";
    $sqlst=$conn_p->prepare($st);
    $bindParamArray=array("id"=>$id);
    $sqlst->execute($bindParamArray);   
    $row=$sqlst->fetch();   
    return $row;
}

function getData()
{
    global $conn_p; 
    $st= "select * from table2";
    $sqlst=$conn_p->prepare($st);
    $sqlst->execute();  
    $row=$sqlst->fetchAll();    
    return $row;
}
........same other functions

$data = getData();

foreach ($data as $dd) {

    $abc[] = abc($dd['id']);
    $xyz[] = xyz($dd['no']);
    //some other manipulations......
}

echo json_encode(array('data1'=>$abc,'data2'=>$xyz));

运行sql命令时

select * from pg_stat_activity

它显示了多个连接。(我的服务器管理员告诉我)

现在我的问题是:

  • 我需要关闭连接吗?
  • 如果是,那么什么时候关闭呢?
  • 如果出现错误怎么办?

【问题讨论】:

  • 根据设置的具体情况,您可能需要考虑使用持久连接。 php.net/manual/en/pdo.connections.php
  • 您应该考虑使用以下命令关闭 PDO:$conn_p = null;
  • 好的,何时使用 $conn_p = null;我的意思是在我上面的脚本中在哪里写它,在脚本的末尾还是?

标签: php postgresql pdo connection


【解决方案1】:

一些建议:

  1. 不,您不需要关闭连接,除非您的脚本运行了很长时间并且您在它进行耗时操作时没有使用它。脚本完成后连接将自动关闭。
  2. 您可能不应该每隔 x 秒从数据库中获取所有行。只有新的或更改的行应该更有效。您真的需要页面中的所有行吗?
  3. 您不应使用较短的时间间隔运行 ajax 调用。而是进行 ajax 调用,并在当前 ajax 调用完成时为下一次调用设置 timeOut。这样请求就不会重叠。

【讨论】:

    【解决方案2】:

    这是我在课堂上用于 postgresql 的。
    和mysql一样。

    $this->dsn = $this->driver . ':host=' . $this->host . ';port=' . $this->port . ';dbname=' . $this->name;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-27
      • 2014-02-02
      • 2013-04-02
      • 2013-12-14
      • 2017-03-29
      • 1970-01-01
      • 1970-01-01
      • 2011-12-24
      相关资源
      最近更新 更多