How do I know how many rows a Perl DBI query returns?

后端 未结 7 867
遥遥无期
遥遥无期 2020-12-15 18:51

I\'m trying to basically do a search through the database with Perl to tell if there is an item with a certain ID. This search can return no rows, but it can also return one

7条回答
  •  被撕碎了的回忆
    2020-12-15 19:19

    The only reliable way to find out how many rows are returned by a SELECT query is to fetch them all and count them. As stated in the DBI documentation:

    Generally, you can only rely on a row count after a non-SELECT execute (for some specific operations like UPDATE and DELETE), or after fetching all the rows of a SELECT statement.

    For SELECT statements, it is generally not possible to know how many rows will be returned except by fetching them all. Some drivers will return the number of rows the application has fetched so far, but others may return -1 until all rows have been fetched. So use of the rows method or $DBI::rows with SELECT statements is not recommended.

    However, when you get down to it, you almost never need to know that in advance anyhow. Just loop on while ($sth->fetch) to process each row or, for the special case of a query that will only return zero or one rows,

    if ($sth->fetch) {
      # do stuff for one row returned
    } else {
      # do stuff for no rows returned
    }
    

提交回复
热议问题