Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

basic dbi question

by Anonymous Monk
on Dec 01, 2010 at 19:19 UTC ( [id://874714]=perlquestion: print w/replies, xml ) Need Help??

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

venerable monks

I am new to perl and getting used to the dbi. Is there any way i can shorten this code when i don't have any parameters to pass to my query

$sql = "select cols from $tableName where col=constant and col2 =const +ant"; my $sth = $db->prepare($sql); $sth->execute or die "SQL Error: $DBI::errstr\n"; while ($row = $sth->fetchrow_hashref) { #analyse each row
It seems long winded for perl!

thanks a lot

Replies are listed 'Best First'.
Re: basic dbi question
by ikegami (Patriarch) on Dec 01, 2010 at 19:49 UTC

    I don't understand the question. You don't pass any parameters to your query.

    You couldn't even if you wanted to. Replaceable parameters only work for values. For identifiers such as table names, you need to use $dbh->quote_identifier.

    my $sth = $dbh->prepare(" SELECT cols FROM ".$dbh->quote_identifier($tableName)." WHERE col=constant AND col2=constant "); $sth->execute(); while (my $row = $sth->fetchrow_hashref) { ... }
      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

        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

        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.

Re: basic dbi question
by sundialsvc4 (Abbot) on Dec 01, 2010 at 21:16 UTC

    If you find yourself repeating yourself repeating yourself too much too much, you can also cobble-together a little sub vaguely like this one:

    sub prepare_execute { # (sql, what) my ($sql, $what) = @_; my $sth=$dbh->prepare($sql) # '$dbh' IS GLOBAL... or die "can't prepare $what: $dbh->errstr"; $sth->execute or die "can't execute $what: $sth->errstr"; return $sth; }
    ... or whatever else you want to put in there.   This is “strictly shorthand,” but sometimes shorthand is what you really want.   If you find yourself doing the same thing over and over and over again, put it into a local sub.

      i wanted the prepare statement outside the loop because i believe it is quicker that way? I have millions of records
Re: basic dbi question
by afoken (Chancellor) on Dec 02, 2010 at 14:46 UTC

    ... also read about the RaiseError attribute -- it can save you a lot of typing.

    Alexander

    --
    Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://874714]
Approved by ww
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (2)
As of 2024-04-16 21:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found