<?php
$conn = mysql_connect($dbhost, $dbuser, $dbpw) or die('Could not connect: ' . mysql_error());
mysql_select_db($dbname) or die('Could not select database');
mysql_query("set names 'utf8'");
echo "other work of waste time \n";
sleep("20"); // 其他费时工作
//检查数据库是否失去连接 如果数据库 $conn 超时失效则重新联接
$checkDbLink = mysql_query("set names 'utf8'",$conn);
if(!$checkDbLink){
getDbLink($conn);
}
$sqlData = "select id,dateline,page_num,top_channel_id from cms_article where id > 5 limit 1 ";
$rs = mysql_query($sqlData,$conn);
$line = mysql_fetch_array($rs);
echo $line['id']."\n";
function getDbLink(&$conn){
global $dbhost, $dbuser, $dbpw,$dbname;
mysql_close($conn); // 失去数据库连接,如果要重建连接必须要 关闭原来的资源然后再重新建立
$conn = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpw) or die('Could not connect: ' . mysql_error());
mysql_select_db($dbname,$conn) or die("Could not select database ".mysql_error());
}
mysql_close($conn);
?>
处理成函数:
// 检查数据库是否失去连接,如果失去连接则重新建立链接
function checkDbLink($dbhost, $dbuser, $dbpw,$dbname,&$conn){
$rsCheck = mysql_query("set names 'utf8'",$conn);
if(!$rsCheck){
mysql_close($conn); $conn = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpw) or die('Could not connect: ' . mysql_error());
mysql_select_db($dbname,$conn) or die("Could not select database at common.php ".mysql_error());
mysql_query("set names 'utf8'",$conn);
}
}
private function dbQuery($sql) {
try{
$result = mysql_query($sql, $this->conn);
}catch (Exception $e) {
$mysqlErrno = mysql_errno();
if(in_array($mysqlErrno, array(2006,2013))) {
$this->getConn();
$result = $this->dbQuery($sql);
}
}
return $result;
}
或者最简单在脚本最前面加一条语句
mysql_query("set wait_timeout = 50");