bradcathey has asked for the wisdom of the Perl Monks concerning the following question:

Fellow Monasterians,

Curious about fetching data from MySQL with the DBI. Besides those instances where only need to prepare-once-for-many-executes-to-follow, what are the pros and cons of fetch... vs select...? Is fetch faster? Thanks.


—Brad
"The important work of moving the world forward does not wait to be done by perfect men." George Eliot

Replies are listed 'Best First'.
Re: fetchrow/all vs selectrow/all
by Aristotle (Chancellor) on Nov 26, 2005 at 00:56 UTC

    select(row|all) will prepare and execute a query in one step. That’s handy when you only need to run a query once, but if you repeat it, it will re-prepare the query every time.

    If you prepare the query manually, you can execute it repeatedly without preparing it more than once.

    Makeshifts last the longest.

Re: fetchrow/all vs selectrow/all
by TedPride (Priest) on Nov 25, 2005 at 21:44 UTC
    Isn't select for queries, and fetch for getting results? What are you asking exactly? Getting results as an array is faster than as a hash, and selecting specific fields is faster than using *. Set up repeating queries with placeholders so you only have to initialize them once, and use IN if you need to select a small set of records, rather than querying x number of times.

    EDIT: Oh, I see what you want to know. Use IN and fetchrow rather than multiple selectrows.

      Alrighty then. How do these two compare? (all strict, of course)

      $stmt = "SELECT * FROM mytable WHERE id = $myid"; $sth= $dbh->prepare($stmt); $sth->execute; $results = $sth->fetchall_arrayref({}); __versus__ $stmt = "SELECT * FROM mytable WHERE id = $myid"; $results = $dbh->selectall_arrayref($stmt);

      Advantages of one over the other?


      —Brad
      "The important work of moving the world forward does not wait to be done by perfect men." George Eliot

        Note that you should probably use placeholders. It’s so easy with DBI that there’s rarely a reason not to.

        my $stmt = "SELECT * FROM mytable WHERE id = ?"; my $sth = $dbh->prepare( $stmt ); $sth->execute( $myid ); my $results = $sth->fetchall_arrayref( {} ); # or my $stmt = "SELECT * FROM mytable WHERE id = ?"; my $results = $dbh->selectall_arrayref( $stmt, undef, $myid );

        Then you can also further optimise the first case by saying

        my $sth = $dbh->prepare_cached( $stmt );

        In that case, because the placeholder-adorned query is always the same, you might even end up preparing the statement only once during your entire runtime.

        Makeshifts last the longest.