Thursday, July 21, 2011

connect to mysql with perl

Just as the title says:
Install the package libdbi-perl.

Create the databases/tables/users/permissions as needed.
This is a sample script:

#!/usr/bin/env perl

use DBI;

# MySQL CONFIG VARIABLES
$host = "localhost";
$database = "your_database";
$tablename = "test";
$user = "this_is_me";
$pw = "this_is_my_password";

#connect to database
$connect = DBI->connect('DBI:mysql:database=' . $database . ';host=' . $host, $user, $pw);


# select stuffs
my $sel = $connect->prepare("select * from $tablename");
$sel->execute;
while( @row = $sel->fetchrow_array) {
    foreach (@row) {
 print;
 print "\t";
    }
    print "\n";
}

This code prints every row, tab-separated from the selected table.

No comments:

Post a Comment