最近遇到了一個非常奇怪的問題,php往mysql中讀寫數據,過一天就不work了.一直不能求解,指導有一天,有人對我說mysql 連接可能會超時.
google了一下,發現mysql connection默認的超時時間爲8小時.當時我想讓我的這個連接永久不超時,該怎麼辦呢?
有人說在mysql配置文件my.cfg中[mysqld]中添加
wait _timeout =31536000 (這裏的這個數字的單位是秒,31536000秒=365天,這也是可設置的最大值)
這個解決辦法不是最好的,因爲這個"一年" != 永久..如何才能讓該連接永久不超時呢?
然後,我繼續google....
最後找到了我需要的答案,非常優雅的方式:
- function reconnect(){
- if (!mysql_ping ($this->db)) {
- //here is the major trick, you have to close the connection (even though its not currently working) for it to recreate properly.
- mysql_close($this->db);
- $this->connect();
- }
- }
其中的mysql_ping()用來判斷連接是否已經被斷開了,若是斷開了,關閉當前的鏈接,重新創建新的連接.
這樣,只要發現連接被斷開了,即可重新連接了.
參考: http://php.net/manual/en/function.mysql-ping.php
【轉自】http://jinchishuxue.iteye.com/blog/1115148