如何在PDO中获取查询语句的类型? [英] How to get the type of a query statement in PDO?

查看:89
本文介绍了如何在PDO中获取查询语句的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MySQL参考手册中,数据定义语句和数据操作语句之间的区别.

现在,我想知道查询是否插入数据库记录,更新一条记录,删除一条记录或修改表结构等等,或者更确切地说,是受影响的行的确切数量,但前提是它适用./p>

例如,语句

 SELECT *
FROM SomeTable
WHERE id=1 OR id=2
 

返回许多受影响的行(在本例中为 2 ),但是使用SELECT语句,数据库中没有任何修改,因此该行将为 0 .

如何获取查询类型?

解决方案

我一直在寻找相同的答案,却偶然发现本文.最近一次更新是在八月.其中有一个部分:确定语句的类型"您基本上可以做出以下假设:(从文章中复制)

  • 如果columnCount()为零,则该语句未生成结果集.相反,它修改了行,您可以调用rowCount()来确定受影响的行数.
  • 如果columnCount()大于零,则该语句产生一个结果集,您可以提取行.要确定有多少行,请在获取它们时对其进行计数.

我将为您省去麻烦,只需将代码示例粘贴到此处

$sth = $dbh->prepare ($stmt);
$sth->execute ();
if ($sth->columnCount () == 0)
{
    # there is no result set, so the statement modifies rows
     printf ("Number of rows affected: %d\n", $sth->rowCount ());
}
else
{
    # there is a result set
    printf ("Number of columns in result set: %d\n", $sth->columnCount ());
    $count = 0;
    while ($row = $sth->fetch (PDO::FETCH_NUM))
    {
    # display column values separated by commas
       print (join (", ", $row) . "\n");
       $count++;
    }
}

In the MySQL Reference Manual, there's distinction between data definition statements and data manipulation statements.

Now I want to know if a query inserts a database record, updates one, deletes one or modifies the table structure and so on, or, more precisely, the exact number of affected rows, but only if it is applicable.

For example, the statement

SELECT *
FROM SomeTable
WHERE id=1 OR id=2

returns a number of affected rows (in this case 2), but with the SELECT statement, there's nothing modified in the database, so that number would be 0.

How to get the type of query?

解决方案

I was looking for the same answer and stumbled across this article. It was last updated in August. In it, there is a section: "Determining the Type of a Statement" You basically can make the following assumptions: (copied from the article)

  • If columnCount() is zero, the statement did not produce a result set. Instead, it modified rows and you can invoke rowCount() to determine the number of affected rows.
  • If columnCount() is greater than zero, the statement produced a result set and you can fetch the rows. To determine how many rows there are, count them as you fetch them.

I'll save you the trouble and just paste the code sample here

$sth = $dbh->prepare ($stmt);
$sth->execute ();
if ($sth->columnCount () == 0)
{
    # there is no result set, so the statement modifies rows
     printf ("Number of rows affected: %d\n", $sth->rowCount ());
}
else
{
    # there is a result set
    printf ("Number of columns in result set: %d\n", $sth->columnCount ());
    $count = 0;
    while ($row = $sth->fetch (PDO::FETCH_NUM))
    {
    # display column values separated by commas
       print (join (", ", $row) . "\n");
       $count++;
    }
}

这篇关于如何在PDO中获取查询语句的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆