I created my first module, really a class I guess. It's called My::DB and it stores the connection info for my various databses ( Postgres / Sqlite ). I hate typing the DB info into every program so I tried to make a module out of it.
Credited for helping me learn this:
Object Oriented Perl
Intermediate PerlHow does it look, what should I be doing differently?
My::DB
package My::DB;
use strict;
use DBI;
# Postgres Username/Password
$My::DB::pg_username = 'my_username';
$My::DB::pg_password = 'my_password';
sub new {
my $data = $_[1];
my $dbh;
if ( $data->{server} eq 'pg' ) {
$dbh = DBI->connect("dbi:Pg:dbname=$data->{db};user=$My::DB::p
+g_username;password=$My::DB::pg_password")
or die "Unable to connect: $DBI::errstr\n";
$dbh->{PrintError} = 1;
$dbh->{RaiseError} = 1;
}
if ( $data->{server} eq 'sqlite' ) {
$dbh = DBI->connect("dbi:SQLite:dbname=$data->{db}","","",{Pri
+ntError => 1,AutoCommit => 1});
}
return $dbh;
}
Main Code
#!/usr/bin/perl -w
use strict;
use My::DB;
# connect SQLITE
my $dbh = My::DB->new({server => 'sqlite', db => 'test.db'});
# connect PostgreSQL
#my $dbh = My::DB->new({server => 'pg', db => 'test'});
my $sth_select = $dbh->prepare("SELECT * FROM tbl1");
$sth_select->execute;
while ( my @row = $sth_select->fetchrow ) {
print "@row \n";
}
Edit: Updated using plobsing's suggestion.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.