in reply to Re: basic dbi question
in thread basic dbi question

thats what i was trying to say - normally when i write something like this i have 'col=?' but in this case the value of col1 is known in advance so 'col1=known_value'. i was wondering if i could make the statement shorter given the fact there aren't any values being passed. sorry about the poor wording of the question

Replies are listed 'Best First'.
Re^3: basic dbi question
by wallisds (Beadle) on Dec 01, 2010 at 21:07 UTC

    Are you looking for a way to shorten the method to get your result out of the query? Like a way to replace execute, prepare, fetch?
    If so, check out CPAN on DBI:
    http://search.cpan.org/~timb/DBI-1.615/DBI.pm

    Here are some my favorites... For one row of results I usually like to use:

    my ($col1, $col2, $col3) = $dbh->selectrow_array($query);

    For multiple rows I like the array ref methods. Here is one right from CPAN (http://search.cpan.org/~timb/DBI-1.615/DBI.pm#selectall_arrayref)

    my $emps = $dbh->selectall_arrayref( "SELECT ename FROM emp ORDER BY ename", { Slice => {} } );

    To then access your result you can use this loop

    foreach my $emp ( @$emps ) { print "Employee: $emp->{ename}\n"; }

    There is a lot of information on DBI in CPAN.

    Dawn

Re^3: basic dbi question
by ikegami (Patriarch) on Dec 02, 2010 at 01:04 UTC

    i was wondering if i could make the statement shorter

    I presume you mean the code snippet rather than some specific but unspecified statement. If so, you already did. ->execute($val1, $val2) became ->execute().

    What else do you want? You obviously can't skip preparing and executing the statement, and you can't skip fetching the result. That really doesn't leave anything to remove. You could combine prepare and execute, though.

    my $sth = prepare_and execute($dbh, " SELECT cols FROM ".$dbh->quote_identifier($tableName)." WHERE col=constant AND col2=constant "); while (my $row = $sth->fetchrow_hashref) { ... }

    Up to you to write prepare_and execute, but it's trivial.

    DBI has shortcuts for collecting your data, but you didn't show how you use the data you fetch.