Perl DBI Connect Example

Here is a sample code snippet to connect and access an informix database using Perl DBI

  1. #!/usr/bin/perl
  2.  
  3. # DBI module
  4. use DBI ;
  5.  
  6. # Database handler
  7. $dbh = DBI->connect("DBI:Informix:$db_name");
  8.  
  9. # Statement handler
  10. $sth = $dbh->prepare("$sql");
  11.  
  12. # Execute statement
  13. $sth->execute();
  14.  
  15. # For each row in the table
  16. while (@row = $sth->fetchrow_array())
  17. {
  18. # Push the row into the output table
  19. push(@table, [@row]);
  20. }
  21.  
  22. # Finish statement
  23. $sth->finish();
  24.  
  25. # Disconnect from database
  26. $dbh->disconnect();
  27.  
  28. # For each row
  29. for ($i = 0; $i <= $#table; $i++)
  30. {
  31. # For each column value
  32. for ($j = 0; $j <= $#{$table[$i]}; $j++)
  33. {
  34. # Print field value
  35. print "$table[$i][$j] ";
  36. }
  37.  
  38. print "\\n";
  39. }
  40.  
  41. # if the statement is not a select u can use : $dbh->do($sql);

Leave a Reply

%d bloggers like this: