perl: help with DBI


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting perl: help with DBI
# 1  
Old 05-25-2010
perl: help with DBI

Hi there, I have a bit of code similar to below (which ive actually got from perldoc, but mine is similar enough)

Code:
 
  $sth = $dbh->prepare(q{ SELECT region, sales FROM sales_by_region });
  $sth->execute;
  my ($region, $sales);

  # Bind Perl variables to columns:
  $rv = $sth->bind_columns(\$region, \$sales);


  while ($sth->fetch) {
      print "$region: $sales\n";
  }

I wanted to find a way of testing to see if the result set was empty so that within my while loop i could print "sorry, result set is empty\n" instead of just printing nothing (which is what print "$region: $sales\n"; would do as there are no results ...)

how can I add a test for an empty record set into here?

Any help would be greatly appreciated
# 2  
Old 05-25-2010
Not sure if this will work for you, but why not try it:
Code:
while ($sth->fetch) {

 if ($region ne "" && $sales ne "") {
      print "$region: $sales\n"; 
 }
 else {
      print "Sorry, result set is empty.\n";
 }

}

# 3  
Old 05-25-2010
What database are you using? There may be a way to code the SQL to return you some count or indicator when no rows are returned from your SELECT.

There is also a method called 'rows', but it does not work for SELECT statements.

From perldoc DBI:

Code:
$rv = $sth->rows;

Returns the number of rows affected by the last row-affecting command, or -1 if the number of rows is not known or not available.

Generally, you can only rely on a row count after a non-SELECT execute (for some specific operations like UPDATE and DELETE), or after fetching all the rows of a SELECT statement.

For SELECT statements, it is generally not possible to know how many rows will be returned except by fetching them all. Some drivers will return the number of rows the application has fetched so far, but others may return -1 until all rows have been fetched. So use of the rows method or $DBI::rows with SELECT statements is not recommended.

One alternative method to get a row count for a SELECT is to execute a "SELECT COUNT(*) FROM ..." SQL statement with the same "..." as your query, and then fetch the row count from that.

# 4  
Old 05-25-2010
thank you for your responses, there's plenty there to point me in the right direction

Cheers
# 5  
Old 05-26-2010
Quote:
Originally Posted by hcclnoodles
...
I wanted to find a way of testing to see if the result set was empty so that within my while loop i could print "sorry, result set is empty\n"
...
If the result set was empty, control wouldn't even go inside the while loop; the "fetch" method wouldn't run even once.

Quote:
...
instead of just printing nothing (which is what print "$region: $sales\n"; would do as there are no results ...)
Again, "printing nothing" is not possible because the condition for the while loop would fail the first time itself.

Here's an Oracle example:

Code:
$
$
$ # check if the table "sales_by_region" has data in it
$ echo "select * from sales_by_region;" | sqlplus -s test/test
 
no rows selected
 
$
$ # so there's no data in it
$ # display the content of the Perl program "fetchsales.pl"
$ cat -n fetchsales.pl
    1  #!perl
    2  use DBI;
    3  use vars qw($dbh $sth $region $sales $rv);
    4
    5  $dbh = DBI->connect('dbi:Oracle:', 'test', 'test');
    6  $sth = $dbh->prepare(q{ SELECT region, sales FROM sales_by_region });
    7  $sth->execute;
    8  my ($region, $sales);
    9  # Bind Perl variables to columns:
   10  $rv = $sth->bind_columns(\$region, \$sales);
   11  while ($sth->fetch) {
   12    print "$region: $sales\n";
   13  }
   14  $sth->finish();
   15  $dbh->disconnect();
$
$ # run the program
$ perl fetchsales.pl
$
$

As you can see, the Perl program printed nothing because control did not go to the while loop at all.


Quote:
Originally Posted by pseudocoder
Not sure if this will work for you, but why not try it:
Code:
while ($sth->fetch) {
 
 if ($region ne "" && $sales ne "") {
      print "$region: $sales\n"; 
 }
 else {
      print "Sorry, result set is empty.\n";
 }
 
}


This technique would backfire if there was a record in table with a NULL value for either region column, or sales column or both !

Code:
$
$
$ # check the data in the "sales_by_region" table
$ echo "select * from sales_by_region;" | sqlplus -s test/test
       ID REGION          SALES
---------- ---------- ----------
        1 East
        2                599.75
        3
        4 South           273.9
 
4 rows selected.
 
$
$
$ # "sales" is NULL for id=1, "region" is NULL for id=2
$ # and both are NULL for id=3
$
$ # display the content of the Perl program "fetchsales.pl"
$ cat -n fetchsales.pl
    1  #!perl
    2  use DBI;
    3  use vars qw($dbh $sth $region $sales $rv);
    4  $dbh = DBI->connect('dbi:Oracle:', 'test', 'test');
    5  $sth = $dbh->prepare(q{ SELECT region, sales FROM sales_by_region });
    6  $sth->execute;
    7  my ($region, $sales);
    8  # Bind Perl variables to columns:
    9  $rv = $sth->bind_columns(\$region, \$sales);
   10  while ($sth->fetch) {
   11    if ($region ne "" && $sales ne "") {
   12      print "$region: $sales\n";
   13    } else {
   14      print "Sorry, result set is empty.\n";
   15    }
   16  }
   17  $sth->finish();
   18  $dbh->disconnect();
   19
$
$ # run the program
$ perl fetchsales.pl
Sorry, result set is empty.
Sorry, result set is empty.
Sorry, result set is empty.
South: 273.9
$
$

tyler_durden
This User Gave Thanks to durden_tyler For This Post:
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Perl DBI error

Hi All, I installed DBI module in a non INC location and using it in my script via "use lib". But it throw the below error at the "use DBI" step. Please help Usage: DBI::_install_method(dbi_class, meth_name, file, attribs=Nullsv) at /xx/xxx/xxxxx/xxxxx/oracle/lib/DBI.pm/oracle/lib/DBI.pm line... (2 Replies)
Discussion started by: prasperl
2 Replies

2. UNIX for Advanced & Expert Users

Perl's DBI Module on OS X - uninstallable?

i've been struggling with installing the Perl DBI & DBD modules all weekend, and I'm getting close, but no cigar as of yet. When I run the perl script db.pl I get the following mismatch error: Mon Apr 19 09:43:29 EDT 2010 /Library/Perl/DBD-mysql-4.011 -> peterv@MBP17.local<515>$: db.pl | tee... (0 Replies)
Discussion started by: peterv6
0 Replies

3. Shell Programming and Scripting

connect to MySQL from Perl using DBI

Hi, I want to connect perl with the mysql to select and so on but the connection don't work code #!/usr/bin/perl BEGIN { # PERL MODULES WE WILL BE USING use DBI; $dbh = DBI->connect('DBI:mysql:C:\Program Files\MySQL\MySQL Server 5.0\data\db1','','pass') or die $DBI::errstr;} #... (1 Reply)
Discussion started by: eng_shimaa
1 Replies

4. Shell Programming and Scripting

perl DBI inserting date\time

hi there, my mysql database has a date/time field using the standard mysql date|time format of 2009-08-31 00:16:44 when inserting into this field using perl DBI, is there is an easy way to insert the current date/time in without having to preformat the date/time string in perl before... (3 Replies)
Discussion started by: hcclnoodles
3 Replies

5. Shell Programming and Scripting

Installing Perl DBI and DBD

Hi, i have some queries on installing the Perl DBI and the DBD Oracle. I know that i have to install the DBI first. I have the source files in a folder in my home directory.The commands to install arecd /home/DBI Perl Makefile.PL make make installI would like to know, after executing these... (4 Replies)
Discussion started by: new2ss
4 Replies

6. Programming

perl dbi to oracle getting disconnect_all for oracle dbi help

hi i am trying to connect to an oracle database using dbi and i get this :: Driver has not implemented the disconnect_all method. at /opt/perl/lib/site_perl/5.8.0/sun4-solaris/DBI.pm line 575 END failed--call queue aborted. for all i know, the script was working earlier, but has... (1 Reply)
Discussion started by: poggendroff
1 Replies

7. Shell Programming and Scripting

perl DBI/DBD Module -in cygwin

Hi all, I am trying to install the DBI module in perl using perl -MCPAN -e shell install 'DBI' --It is installing into the nuild directory properly but when it try to make it is saying NOT OK -I tried to copy the module manually to the /lib/perl5/vendor_perl ... (3 Replies)
Discussion started by: jambesh
3 Replies

8. Shell Programming and Scripting

PERL DBI module install

We ran into an issue trying to install DBI and DB2 modules for perl for AIX from the link http://www-306.ibm.com/software/data/db2/perl/ We tried to install the DBI module using bash# perl -MCPAN -e 'install DBI' command. However we ended up with the following error. Stop. ... (3 Replies)
Discussion started by: jerardfjay
3 Replies

9. Shell Programming and Scripting

Perl DBI - Bind Parameters Problem

I have a SQL statement that includes a UNION that I can't get to work when I bind the parameters. (I am binding the parameters to prevent SQL injection.) Does anybody have any suggestion on how I can use a SQL statement that includes a UNION and bind the params? Code would be something like... (1 Reply)
Discussion started by: mh53j_fe
1 Replies

10. Programming

Perl DBI install with gcc compiler

I want to install the Perl DBI module on to my solaris ultra 10. Solaris ultra 10 does not come with a C compiler so I downloaded gcc compiler. Then I ran install as follows: # cd DBI-1.30 # ls blib DBI.xs Driver.xst Perl.c test.pl Changes dbi_sql.h ... (2 Replies)
Discussion started by: photon
2 Replies
Login or Register to Ask a Question