首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在PHP中正确关闭数据库连接

在PHP中正确关闭数据库连接
EN

Stack Overflow用户
提问于 2012-02-28 09:21:34
回答 1查看 847关注 0票数 1

我在PHP数据库连接方面遇到了一些疑问。既然我不能在我的方法上放一个很大的try/catch/finally块(Java风格),那么当大小/逻辑趋于增长时,正确关闭所有连接和准备好的语句的最佳方法是什么?考虑下一种方法,一切都是正确的吗?

代码语言:javascript
复制
public function createRegister($register) {
        $this->openConnection();

        $query = "INSERT INTO register (username, password, email, confirmationToken) VALUES (?, ?, ?, ?)";
        $result = $this->mysqli->query($query);

        if ($statement = $this->mysqli->prepare($query)) {  
            $statement->bind_param("ssss", $register->username, $register->passwordHash, $register->email, $register->confirmationToken);

            if (!$statement->execute()) {
                $this->closeConnection();
                throw new DAOException("Failed to execute statement: " . $statement->error);
            }

            $statement->close();

        } else {
            $this->closeConnection();
            throw new DAOException("Failed to prepare statement: " . $this->mysqli->error);
        }

        $this->closeConnection();
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-02-28 09:25:45

您仍然可以在PHP中使用try/catch:

代码语言:javascript
复制
public function createRegister($register) {

    $this->openConnection();

    $query = "INSERT INTO register (username, password, email, confirmationToken) VALUES (?, ?, ?, ?)";

    try {

        // This line is not needed
        // $result = $this->mysqli->query($query);

        if ($statement = $this->mysqli->prepare($query)) {

            $statement->bind_param("ssss", $register->username, $register->passwordHash, $register->email, $register->confirmationToken);

            if (!$statement->execute()) {                   
                throw new DAOException("Failed to execute statement: " . $statement->error);
            }

            $statement->close();

        } else {
            throw new DAOException("Failed to prepare statement: " . $this->mysqli->error);
        }
    } catch (Exception $e) {

        if ((isset($statement)) && (is_callable(array($statement, 'close')))) {
            $statment->close();
        }

        $this->closeConnection();

        throw $e;
    }

    $this->closeConnection();
}

这对于为一个特定任务建立连接很有效,但是如果您希望为也需要访问相同模式的多个任务共享相同的连接,该怎么办呢?您可能希望考虑一种更高级的解决方案,使用单例/工厂模式创建和访问数据库连接。我发布了这样一个example,作为对另一个问题的解决方案。它有点高级,但一旦你掌握了它,它的性能就会更好。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9475038

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档