Showing posts with label dbi. Show all posts
Showing posts with label dbi. Show all posts

Monday, November 8, 2010

Using perl to create hash tables like your mysql tables

The subroutine Below will take an array of table names and put the columns in a hash, then grab rows and match said rows with said field/column. So that $tableData('salesdatafirst_name') would be the value for the first name column in the tables sales data, in the row based on your condition in the second query of the subroutine.


sub get_table_data {
foreach(@_){
my @ColumnNames;
$data_name = $_;
$dbh = DBI->connect($connectionInfo,$userid,$passwd) or print "Couldn't connect to database: ". DBI->errstr;
$sql = "SHOW COLUMNS FROM $data_name";
$str = $dbh->prepare($sql) or print "Couldn't prepare query: ". DBI->errstr;
$str->execute() or print "Couldn't execute query: ". DBI->errstr;
while (@querytwo = $str->fetchrow_array()) { #loop thru results
$tableData{$data_name.$querytwo[0]}='';
$tableHashHelper = $data_name.$querytwo[0];
push(@ColumnNames, $tableHashHelper);
}

$sql = "SELECT * FROM $data_name WHERE condition = '$yourcondition'";
$str = $dbh->prepare($sql) or print "Couldn't prepare query: ". DBI->errstr;
$str->execute() or print "Couldn't execute query: ". DBI->errstr;
while (@Q = $str->fetchrow_array()) { #loop thru results
for ($i=0; $i<=$#Q; $i++) {
$tableData{$ColumnNames[$i]} = $Q[$i];
}
}
undef(@tableColumnNames);
$dbh->disconnect();
}

Saturday, November 6, 2010

Using DBI putting field / column names in a hash table

use DBI;
use DBD::mysql;
use strict;
use warnings;

my $database = "ci";
my $host = "localhost";
my $port = "3306";
my $tablename = "happy";
my $user = "root";
my $pw = "wouldntyouliketoknow";

my $dsn = "dbi:mysql:$database:localhost:3306";
my $connect = DBI->connect($dsn, $user, $pw);

my $query = "SHOW COLUMNS FROM $tablename";
my $sth = $connect->prepare($query);
$sth->execute();
my %hash;
my @ary;
while(@ary = $sth->fetchrow_array){
$hash{$ary[0]}= '';
}
my $key;
my $value;

print "\n";
while (($key, $value) = each(%hash)){
print $key.", ".$value."\n";
}

Same as the perl script before, but using DBI module instead of Mysql Module.