Small Doubt regarding DB-Select

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • koti688
    New Member
    • Oct 2008
    • 11

    Small Doubt regarding DB-Select

    I have two files like below.

    1st file : mail.pl

    Code:
    #!/usr/bin/perl
    use DBD::mysql;
    use DBI;
    use Utils::DBClass;
    $object = new DBClass( "perltest", "localhost", 3306, "root", "sierra");
    $object -> select_db ("select * from samples");
    2nd file DBClass.pm in a folder named Utils.


    Code:
    package DBClass;
    use DBI;
    @ISA = ('Exporter');
    @EXPORT_OK = ("Connection_check", "new","select_db","insert_db","delete_db","update_db");
    sub Connection_check {
        my($self ) = @_;
        $dsn = "DBI:mysql:database=$self->{_db};host=$self->{_host};port=$self->{_port}";
        $dbh = DBI->connect($dsn,$self->{_user},$self->{_pass});
        return ($dbh)
    }
    sub new
    {
        my $class = shift;
        my $self = {
            _db => shift,
            _host => shift,
            _port => shift,
            _user => shift,
            _pass => shift
        };
        $dbh = Connection_check($self);
        $self->{_dbh} = $dbh;
        bless $self, $class;
        return $self;
    }
    ### Retrieving the Rows ########
    sub select_db{
      my ($obj,$sel) = @_;
      my $sth1 = $dbh->prepare($sel);
      $sth1->execute or die "SQL Error: $DBI::errstr\n";
      my @row;
      while (@row = $sth1->fetchrow_array)
        {
          print "@row \n";
        }
    }
    I am Getting the output for the quiries i mentioned above as below:

    1 Koti 555-5555
    2 Siva 222-2222
    3 Praneet 555-5555
    4 nishitha 08649-257828
    6 Anu 222-2222
    7 Pradeep 555-5555
    8 Asmit 222-2222
    9 Surya 555-5555

    My requirement is getting the out put with out using the "print" statement in the select_db function. i want to get the ouput using "return" function and using "array of arrays".

    can anyone suggest me how to proceed .
  • nithinpes
    Recognized Expert Contributor
    • Dec 2007
    • 410

    #2
    Replace :
    Code:
    while (@row = $sth1->fetchrow_array) 
        { 
          print "@row \n"; 
        }
    with:

    Code:
    my @AoA;
    while (@row = $sth1->fetchrow_array) 
        { 
          push @AoA, [@row] ;   #create array of array
        } 
    return @AoA;    # return array of array

    Comment

    • koti688
      New Member
      • Oct 2008
      • 11

      #3
      Thanks A Lot nithinpes..

      Comment

      Working...