简体   繁体   English

如何在php中保持mysql连接存活

[英]How to keep a mysql connection alive in php

I have a script which loops over tables and fields doing a find and replace. 我有一个脚本循环遍历表和字段进行查找和替换。 The script takes around 4 minutes to complete. 该脚本大约需要4分钟才能完成。 The database is about 1.5GB. 该数据库约为1.5GB。

The problem is that I am somehow loosing the database connection. 问题是我在某种程度上失去了数据库连接。 I am using ADODB to connect to mySQL. 我正在使用ADODB连接到mySQL。 The db connection is opened at the beginning and remains open the whole duration of the script. 数据库连接在开始时打开,并在脚本的整个持续时间内保持打开状态。

The problem disappears when I use the following code: 当我使用以下代码时,问题消失了:

if ($rowCount % 100000 == 0) {
    $db->Execute('USE ' . $db->database);
}

I am not a fan of this solution! 我不是这个解决方案的粉丝!

Any suggestions/explanations/discussions that help me to stop scratching my head would be greatly appreciated! 任何建议/解释/讨论,帮助我停止挠头,将不胜感激!

Use mysqli::ping() to determine if connection is alive. 使用mysqli :: ping()确定连接是否存活。 Connect again if not. 如果没有再连接。

Checks whether the connection to the server is working. 检查与服务器的连接是否正常。 If it has gone down, and global option mysqli.reconnect is enabled an automatic reconnection is attempted. 如果它已关闭,并且启用了全局选项mysqli.reconnect,则会尝试自动重新连接。

This function can be used by clients that remain idle for a long while, to check whether the server has closed the connection and reconnect if necessary. 长时间处于空闲状态的客户端可以使用此功能,以检查服务器是否已关闭连接并在必要时重新连接。

The word you're looking for is 'persistent', and the answer you're looking for is here: 你正在寻找的词是“持久的”,你正在寻找的答案在这里:

mysqli persistent connection mysqli持久连接

You can use one of these methods to make a persistent connection to mysql: 您可以使用以下方法之一与mysql建立持久连接:

Mysqli 库MySQLi

Try using mysqli_connect() with p: prefix for host name. 尝试使用带有p:前缀的mysqli_connect()作为主机名。

PDO PDO

Try using PDO::__construct() with PDO::ATTR_PERSISTENT as a driver option. 尝试将PDO::__construct()PDO::ATTR_PERSISTENT用作驱动程序选项。

You could use mysql_pconnect(); 你可以使用mysql_pconnect(); or equally for ADODB $conn->PConnect(); 或同样适用于ADODB $conn->PConnect(); to create a persistent connection 创建持久连接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM