Sep 13, 2012

Perl connect to Database

#!c:/perl/bin/perl
  use CGI qw(:all);   
  use HTML::Template;   
  use DBI;   
   
  my $dbh = DBI->connect('dbi:mysql:perltest','root','password')  or die "Connection Error: $DBI::errstr\n";      ####MYSQL
  my $db=DBI->connect("dbi:Oracle:local", "scott", "tiger"); ###Oracle
 
  my $sql = "select * from languages";   
  my $sth = $dbh->prepare($sql) or die "SQL Error: $DBI::errstr\n";   
  $sth->execute();   
   
  my $languages = $sth->fetchall_arrayref(
    {   
     language_name => 1,    
     description   => 1
    }   
  );   
   
=cut
while (@row = $sth->fetchrow_array) {
    print "@row\n";
}
=cut   
   
  print header;   
  my $template = HTML::Template->new( filename => 'template2.tmpl' );   
  $template->param( language => $languages );   
  print $template->output(); 

template2.tmpl
#################
    <html>  <br> 
    <head>  <br> 
    <title>Template 3</title>  <br> 
    </head>  <br> 
    <body>  <br> 
    <table>  <br> 
        <tmpl_if name=language>  <br> 
      <tr>  <br> 
        <th>Language</th>  <br> 
        <th>Description</th>  <br> 
      </tr>  <br> 
      <tmpl_loop name="language">  <br> 
      <tr>  <br> 
        <td><tmpl_var name="language_name"></td>  <br> 
        <td><tmpl_var name="description"></td>  <br> 
      </tr>  <br> 
      </tmpl_loop>  <br> 
        <tmpl_else>  <br> 
      Sorry, no languages were found  <br> 
        </tmpl_if>  <br> 
    </table>  <br> 
    </body>  <br> 
    </html>   

No comments:

Post a Comment