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

I am trying to retrieve a query from an access database using ODBC. I have succesfuly connected to the database and selected data on another table. However, a query I am using doesn't return any results. It works if I use it as a query in access, but not in DBI.

use Data::Dumper; use DBI; my $dbh = DBI-> connect('DBI:ODBC:MyDB'); # Catch and display status messages with this error handler. sub err_handler { my ($sqlstate, $msg, $nativeerr) = @_; # Strip out all of the driver ID stuff $msg =~ s/^(\[[\w\s:]*\])+//; print $msg; print "===> state: $sqlstate msg: $msg nativeerr: $nativeerr\n"; return 0; } $dbh->{odbc_err_handler} = \&err_handler; $dbh->{odbc_exec_direct} = 1; my $sql = qq/SELECT * FROM Files WHERE (((Files.Field) Like '*20060906 +*'));/; # the query to execute my $sth = $dbh->prepare($sql); # prepare the query $sth->execute(); # execute the query while ( @row = $sth->fetchrow_array ) { print "@row\n"; }

Replies are listed 'Best First'.
Re: DBI to ODBC
by Corion (Patriarch) on Jun 27, 2007 at 13:52 UTC

    You're not checking any errors and don't have the RaiseError or PrintError attributes on your DBI object. I think that DBI has PrintError set to a true value by default, but I prefer to be explicit there:

    my $dbh = DBI->connect('DBI:ODBC:MyDB',undef,undef,{RaiseError => 1}); ...

    My wild guess is that either DBI does not like the trailing semicolon in your statement - maybe remove that from your statement. The other option is that the ODBC driver, for some weird reason, prefers % over * as a wildcard. The wildcard for Access is * while for most other SQL implementations is %.

Re: DBI to ODBC
by bart (Canon) on Jun 27, 2007 at 19:56 UTC
    Note that MS Access likes a slightly different syntax for its SQL when controlled through ODBC (and thus, through DBI), than it does through the interactive query interface ("query builder"): through ODBC it likes a more standardized SQL. That may occasionally bite you.

    And Corion is right, semicolons in SQL statements often make things not work.

Re: DBI to ODBC
by rpnoble (Sexton) on Jun 28, 2007 at 02:59 UTC
    You have two problems. The first is the semicolon at the end of the SQL Statement. The second is that the * needs to be a %. The ODBC wildcard is the percent sign.