我应该多久关闭一次数据库连接? [英] How often should I close database connections?

查看:184
本文介绍了我应该多久关闭一次数据库连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我在应用程序的初始化中打开数据库连接。这是一个相当小的应用程序,PHP如果相关。

Currently, I'm opening a database connection in my app's initialization. It's a fairly small app, PHP if that's relevant.

我应该连接到数据库,调用,然后关闭和重复这个过程为每个数据库函数我写?

Should I be connecting to the database, making calls, then closing and repeating this process for each database function I write?

例如,我有以下函数从应用程序的初始化中获取$ db变量。

For example, I have the following function which grabs the $db variable from my app's initialization.

function get_all_sections()
{
    global $db;
    $sql = 'select * from sections'; 

    if (!$db->executeSQL($sql, $result))
    {
        throw new Exception($db->getDatabaseError());
        exit();
    }

    $sections = array();

    for ($i = 0; $i < $db->numberOfRows($result); $i++)
    {
        $sections[] = new Section($db->fetchArray($result, MYSQLI_ASSOC));
    }

    return $sections;
}

如果我打开连接然后关闭它,行?

Would it be better if I opened the connection then closed it after I fetched the rows? That seems like a lot of connections that are opened and closed.

推荐答案

如果你有连接池( http://en.wikipedia.org/wiki/Connection_pool )它可以在您需要时抓取新的连接。但是,我会说,处理任何资源为有限的习惯,如果你打开数据库句柄尽可能长的保持它。

If you have connection pooling on (http://en.wikipedia.org/wiki/Connection_pool) its ok to be grabbing a new connection when you need it. HOWEVER, I'd say to be in the habit of treating any resource as "limited" and if you open the db handle keep it around for as long as possible.

这篇关于我应该多久关闭一次数据库连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆