Hi Monks!
I am trying to write a small module to have my sql connection separated from the rest of my applications just in case information like password or username need to be changed.
I am having issues, and I am wondering if someone would have something similar that could help me with what I have.
Here is the module:
#--------------------------------------------------------------
# my module.
#--------------------------------------------------------------
package ModTest;
require Exporter;
our @ISA = qw(Exporter);
our @EXPORT = qw( mysql_connect);
our $VERSION = 1.00;
use Carp qw( confess );
use DBI;
sub connect_mysql {
my $hostname = "mysql.page.com";
my $username = "myusername";
my $password = "mypassword";
my $database = "mydatabase";
my $dbh = \DBI->connect("dbi:mysql:database=$database;host=$hostname"
+,$username,$password)
#bles $dbh; ||
+ confess "Connect to $db failed: $DBI::errstr";
return $dbh;
}
1;
Here is my test Perl script to test the connection:
#!/usr/bin/perl -w
use DBI;
use CGI::Carp qw(fatalsToBrowser);
use ModTest;
print "Content-type:text/html\n\n";
my $sql_dbh = ModTest->connect_mysql();
my $sql = "SELECT * FROM my_table";
my $st = $dbh->prepare($sql)
or die "Preparing MySQL query failed: $DBI::errstr";
$st->execute()
or die "The execution of the MySQL query failed: $DBI::errstr";
while ($row = $st->fetchrow_hashref())
{
print " $row->{first} $row->{last}";
}
$dbh ->disconnect();
Thanks for the help!
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.