使用PDO和mysqli连接mysql数据库过慢的解决办法

 1.在测试数据库连接效率时,会遇到这种情况

<?php
header('content-type:text/html;charset=utf-8');
//1.通过PDO连接数据库
$pStartTime=microtime(true);
for($i=1;$i<=100;$i++){
    $pdo=new PDO('mysql:host=localhost;dbname=test','root','root');
}
$pEndTime=microtime(true);
$res1=$pEndTime-$pStartTime;

//2.通过MySQL连接数据库
$mStartTime=microtime(true);
for($i=1;$i<=100;$i++){
    $con=mysqli_connect('localhost','root','root');
    mysqli_select_db($con,'test');
}
$mEndTime=microtime(true);
$res2=$mEndTime-$mStartTime;
echo $res1.'<br/>'.$res2;
echo '<hr/>';
if($res1>$res2){
    echo 'PDO连接数据库MySQL的'.round($res1/$res2).'倍';
}else{
    echo 'MySQL连接数据库PDO的'.round($res2/$res1).'倍';
}

按照上面代码测试,会出现连接超时(超过30秒),就算是就重复连接3次两次,时间也会比较长。

这时候把localhost改为127.0.0.1连接速度就会变得正常。

测试结果:

0.94578814506531
1.0991640090942


MySQL连接数据库PDO的1倍

 

 

2.另外还有一种方式也可以提升连接速度就是用长连接

<?php
header('content-type:text/html;charset=utf-8');
//1.通过PDO连接数据库
$pStartTime=microtime(true);
for($i=1;$i<=100;$i++){
    $pdo=new PDO('mysql:host=127.0.0.1;dbname=test','root','root', array(PDO::ATTR_PERSISTENT => true));
}
$pEndTime=microtime(true);
$res1=$pEndTime-$pStartTime;

//2.通过MySQL连接数据库
$mStartTime=microtime(true);
for($i=1;$i<=100;$i++){
    $con=mysqli_connect('127.0.0.1','root','root');
    mysqli_select_db($con,'test');
}
$mEndTime=microtime(true);
$res2=$mEndTime-$mStartTime;
echo $res1.'<br/>'.$res2;
echo '<hr/>';
if($res1>$res2){
    echo 'PDO连接数据库MySQL的'.round($res1/$res2).'倍';
}else{
    echo 'MySQL连接数据库PDO的'.round($res2/$res1).'倍';
}

注意连接pdo时的变化

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值