3

我只是想知道,在页面末尾关闭 PHP 中的 MySQL 连接是否很好?有什么优势?关闭它重要吗?

真诚的,乔伊

4

5 回答 5

2

通常不需要使用 mysql_close(),因为非持久打开的链接会在脚本执行结束时自动关闭,但请记住,一旦不再需要资源就立即终止它们始终是一个好习惯。如果您的脚本长时间占用您不再需要的资源,只会让您更接近资源耗尽

于 2012-08-04T12:04:23.797 回答
2

无论如何,PHP 都会在脚本结束时释放任何资源。

例如,最好释放文件资源并锁定文件,因为您的脚本可能会以 1s 形式运行,但您可能只需要在脚本开始时几毫秒的文件。

如果您在开始时使用 SQL 几毫秒,则使用相同的推理,然后只对提取的数据进行处理 - 通过关闭您的连接,您允许另一个连接取代您的位置(MySQL 限制可以同时连接的连接数制成)。

另一方面,如果您在脚本结束时释放它,因为您在脚本的整个执行过程中(间歇性地)使用数据库,那么您只是在做 PHP 在脚本结束时无论如何都会做的事情。

于 2012-08-04T12:05:23.997 回答
0

If you mean using persistent connections: in general (99.99% of the time) it is NOT (!) very wise to use persistent connections. Certainly not when using transactions. The performance penalty for opening and closing connections every request is not that big.

PHP persistent connections are bad because...

  • they cause transactions, table locks, temporary tables, session variables and most other useful features in MySQL to be very dangerous, potentially causing server-wide deadlocks and database errors during page generation.
  • they occupy hundreds of MySQL sockets and threads, increasing the risk of hitting a limit somewhere (open files, mysql settings, kernel limits?).
  • When something break because of persistent connections, it's certain to be extremely difficult to diagnose, since it will only show up after a certain thread has served certain requests in a certain order.
  • with a pool of web servers, one slow web server can back up and consume so many connections it can't use that the other servers can't create connections to complete their requests.

See for instance this article.

http://meta.wikimedia.org/wiki/Why_persistent_connections_are_bad

In general it is also good programming practice to explicitly release all resources you acquire as soon as possible since they can then be used by competing scripts of routines. Using constructors and destructors ('smart resources') is a good way to do this. In PHP it is possible your script ends with a fatal error in which case you get no chance to release them yourself.

于 2012-08-04T12:55:15.650 回答
0

是的,使用后关闭连接是一种很好的做法,它可以减轻数据库的负担。性能会提高。应始终在使用后释放资源,以便其他用户可以使用它们。

于 2012-08-04T12:03:59.037 回答
0

$conn = new mysqli("localhost","Username","Password","Db_name");

$sql = "SELECT * FROM `your_table_name`";

$connStatus = $conn->query($sql);

$numberOfRows = mysqli_num_rows($connStatus);

$numberOfRows; 

//this echo out the total number of rows returned from the query

$conn->close();
于 2019-02-18T11:20:59.880 回答