使用参数化查询减慢SQLSRV PDO查询性能

时间:2017-08-09 19:05:07

标签: php sql-server performance pdo

我的网络应用程序中有很多查询,并注意到性能不如我想的那么多。所以我删除了参数化变量,查询运行得更快。

$conn = new PDO("sqlsrv:Server=myserver;Database=mydb; MultipleActiveResultSets=false", "user", "pw"); 
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); 
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$getData_query = $conn->prepare("select several_columns
    from myTable 
    where severalstatements = severalstatements
    and this = :that
");
$getData_query->bindValue(':that', 'somestring');
$getData_query->execute();

or

$getData_query = $conn->prepare("select several_columns
    from myTable 
    where severalstatements = severalstatements
    and this = :that
");
$getData_query->execute(array('that'=>'somestring'));

服务器使用pdo_sqlsrv版本4.0.8.0

运行PHP7和SQLserver 2016

如果我运行上述任一上述查询,则需要平均1.15秒才能运行。 如果我删除参数化部分,只需使用

and this = 'somestring'

查询运行时间为.110秒,速度更快!

我做错了什么?为什么参数化方法要慢得多?

1 个答案:

答案 0 :(得分:1)

你正在尝试做的事情是不正确的。

您需要使用bindParam,这是您尝试绑定this的第二个语句that

$conn = new PDO("sqlsrv:Server=myserver;Database=mydb; MultipleActiveResultSets=false", "user", "pw"); 
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); 
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$getData_query = $conn->prepare("select several_columns
    from myTable 
    where severalstatements = severalstatements
    and this = :that
");
$getData_query->bindParam(':that', 'somestring'); //this line changed
$getData_query->execute();

or

$getData_query = $conn->prepare("select several_columns
    from myTable 
    where severalstatements = severalstatements
    and this = :that
");
$getData_query->execute(array('that'=>'somestring')); // this line changed