wwaayyaa/mysql-timeout

自定义数据库查询超时

1.0.2 2016-09-28 09:51 UTC

This package is not auto-updated.

Last update: 2024-09-28 20:09:08 UTC


README

自定义数据库查询超时

安装

composer.json

{
"require": {
    "wwaayyaa/mysql-timeout":  "dev-master"
  }
}

$ composer install

示例

PHP 代码

    $conf = Conf::$db1;
    print_r($conf);

    $d = new MysqlTimeout($conf);

    echo "now:".time()."\n";
    $r = $d->query('select sleep(2) as `sleep`,2 as `sec`;');
    print_r($r);
    echo "sleep 2s,now:".time()."\n";
    try{
    $r = $d->query('select sleep(5) as `sleep`,5 as `sec`;',3);
    }catch(Exception $e){
        echo sprintf("error message:%s ,error code : %d \n",$e->getMessage(),$e->getCode());
    }
    echo "sleep 5s but timeout is 3s,so throw a error.now:".time()."\n";

    $d = new MysqlTimeout($conf);//must new a MysqlTimeout. because 
    $r = $d->query('select sleep(5) as `sleep`,5 as `sec`;',6);
    print_r($r);
    echo "sleep 5s success,because timeout is 6s. now:".time()."\n";
    
    //Other methods
    $r = $d->update("update dtk_zhibo_chat_log set addtime=now() where id = 6 or id = 17;");
    echo sprintf("success rows:%d \n",$r);
    $r = $d->insert("insert into dtk_zhibo_chat_log (zhiboId,content) values (1292,'test');");
    echo sprintf("primary id:%d \n",$r);

结果

Array
(
    [host] => 127.0.0.1
    [port] => 3306
    [user] => root
    [password] => root
    [dbname] => test
    [charset] => utf8
)
now:1475056910
Array
(
    [0] => Array
        (
            [sleep] => 0
            [sec] => 2
        )

)
sleep 2s,now:1475056912
error message:timeout ,error code : 922922
sleep 5s but timeout is 3s,so throw a error.now:1475056915
Array
(
    [0] => Array
        (
            [sleep] => 0
            [sec] => 5
        )

)
sleep 5s success,because timeout is 6s. now:1475056920
success rows:2
primary id:1036

方法

	/**
     * @return mixed  query data
     */
	public function query($sql, $timeout = 3);

	/**
     * @return int   rows count
     */
	public function update($sql, $timeout = 3);

	/**
     * @return int   data primary id
     */
	public function insert($sql, $timeout = 3);

	/**
     * @return int   rows count
     */
	public function delete($sql, $timeout = 3);

参数

配置

  • 主机 | 必须是 '127.0.0.1'
  • 端口 | 非必须 '3306'
  • 用户 | 必须是 'root'
  • 密码 | 必须是 'root'
  • 数据库名 | 必须是 'text'
  • 字符集 | 必须是 'utf8'
  • 超时 | 非必须 3

超时 (默认: 3)

  • MsyqlTimeout 检查周期为 0.05 秒,
  • 因此 $timeout 参数的最小值为 0.05,
  • 最大值取决于 PHP.ini 中的 max_execution_time 和 MySQL 的 timeout 设置

异常

错误代码

如果查询超时,MysqlTimeout 将抛出异常,异常编号 922922