in reply to basic dbi question

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) { ... }

Replies are listed 'Best First'.
Re^2: basic dbi question
by Anonymous Monk on Dec 01, 2010 at 20:44 UTC
    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.