[Tfug] Let's play "ID this code"! (serious issue actually)

Zack Williams zdwzdw at gmail.com
Sun Aug 23 16:03:49 MST 2009


> But are there any FOSS tools available that'll take apart these
> databases I have now?

Here's some really rough perl code to pull a table out of the ODBC
datasource, and put it into a CSV file.  It's ripped straight from a
project I did a while ago, so it's likely incomplete.

--
use DBI;

my $dbh = DBI->connect('DBI:ODBC:' . $config{"db_name"},
$config{"db_login"}, $config{"db_password"});

my $sql = "SELECT * FROM TABLENAME";

my $sth = $dbh->prepare( $sql )
	or die "Couldn't prepare statement: " . $dbh->errstr;
$sth->execute()             # Execute the query
	or die "Couldn't execute statement: " . $sth->errstr;

while (my @data = $sth->fetchrow_array()) { # grab a row of data

open(TBL,">" . $filename)  # open file for writing
	or die "Problem with output file: " . $filename;

while (my @data = $sth->fetchrow_array()) { # grab a row of data
	my @areNumbers = DBI::looks_like_number( @data ); #find out if this
is a number
		for (my $i = 0; $i < @data; ++$i ) {
			if ( $areNumbers[$i] ) { # if it's a number, print unquoted
				print TBL $data[$i];
			} else {  # if it's not a number, and not null, print with single quotes
				if($data[$i]){
					my $string = $data[$i] ;
					$string =~ s/\s/ /gs; # replace non-printing whitespace with spaces
					$string =~ s/\\/\\\\/gs; # escape backslashes
					$string =~ s/\'/\\\'/gs; # escape single quotes
					print TBL "'" . $string . "'";
				}
			}
			print TBL "," ; # insert comma delimiters
		}
	print TBL "\n"; # end the line
}

--




More information about the tfug mailing list