Google AdSense

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();
}

0 comments: