MySQL数据库连接未关闭:会发生什么? [英] MySQL database connection not closed: what will happen?

查看:607
本文介绍了MySQL数据库连接未关闭:会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用PHP来查询我的网站上的MySQL数据库。请回答以下问题:


  1. 如果我不使用 mysql_close()当我完成查询数据库到底?连接将保持打开?如果是,那么多少时间?如果没有,为什么?

  2. 如果我在
    网页的几个地方打开并关闭MySQL连接,性能如何影响?

  3. 如何 mysql_close()与性能相关?我应该在每次需要访问数据库时打开一个新连接,还是应该只保留一个连接并最后关闭它?

  4. 如果我不关闭连接,用户尝试
    再次访问一些数据,将使用新连接还是使用旧的
    打开连接?



  • 性能将会在执行过程中自动关闭。

  • 负面影响。打开新的套接字(特别是外部数据库服务器)比保存指向内存中当前连接的指针更昂贵和耗时。
  • 请参阅回答否。 2

  • 对数据的访问将由一个新的PHP请求执行。因此,您将有一个新的数据库连接。没有问题。

  • 我建议在构建阶段打开数据库连接,在整个执行过程中重新使用该连接您的脚本(如果它是基于OO的,为您的数据库连接分配一个类变量,并在整个脚本中使用 $ this-> db ),不要打扰它,因为它会被关闭,即使没有明确声明)。


    I am using PHP to query the MySQL database on my website. Please answer the following questions:

    1. What will happen if I don't use mysql_close() when I am done with querying the database in the end? The connection will remain open? If yes then upto how much time? If no then why?
    2. If I open and close a connection to MySQL at several places in a webpage, how is the performance affected? i.e. connection is made again everytime some access to database is required on a single webpage.
    3. How is mysql_close() related to performance? Should I open a new connection everytime some access to database is required OR should I keep only one connection and close it in the end?
    4. If I don't close the connection, then if the user is trying to access some data again, will the new connection be used or the old open connection will be used?

    解决方案

    1. It will automatically close when the PHP script is done running during destruct phase.
    2. Performance will negatively be affected. Opening a new socket (especially to an external database server) is more expensive and time consuming than just keeping a pointer to the current connection in memory.
    3. See answer no. 2
    4. The access to the data will be performed by a new PHP request. Hence, you will have a new database connection. No problems there.

    I'd advise to open your database connection during construct phase, re-use that connection during the entire execution of your script (if it's OO based, assign a class variable for your database connection and use $this->db during the entire script), and close it during destruction (or don't bother at all closing it, as it will be closed anyway, even when not declared specifically).

    这篇关于MySQL数据库连接未关闭:会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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