#!/usr/bin/perl use strict; use warnings; use DBD::mysql; $|=1; #flush every time the program my $db = 'xxxx'; my $port = '3306'; # default my $host = 'localhost'; # or external my $pass = 'xxxx'; my $user = 'xxxx'; my $table = 'xxxx'; my $checkExist; sub mysql { my $dbh = DBI->connect("dbi:mysql::".$host.":".$port."", "".$user."", "".$pass."", { 'PrintError' => 1, 'RaiseError' => 1 } ) or die "Could not connect to ".$host.": ". $DBI::errstr ."\n"; my $databases = $dbh->do("SHOW DATABASES LIKE '".$db."'") or die "Error: " .dbh->errstr. "\n"; if ($databases eq 1) { printf "Database: ".$db." exists not creating: ".$db."\n"; } else { printf "Database: ".$db." does not exist creating: ".$db."\n"; $checkExist = $dbh->prepare("CREATE DATABASE IF NOT EXISTS `".$db."`") or die "Could not create the: ".$db." error: ". $dbh->errstr ."\n"; if (!$checkExist->execute()) { die "Error: ". $checkExist->errstr ."\n"; } $checkExist->finish(); $dbh->disconnect(); } # End of else $dbh = DBI->connect("dbi:mysql:".$db.":".$host.":".$port."", "".$user."", "".$pass."", { 'PrintError' => 1, 'RaiseError' => 1 } ) or die "Could not connect to ".$host.": ". $DBI::errstr ."\n"; my $tables = $dbh->do("SHOW TABLES FROM `".$db."` WHERE Tables_in_".$db." LIKE '".$table."'") or die "Error: " .dbh->errstr. "\n"; if ($tables eq 1) { printf "Table: ".$table." exists not creating: ".$table."\n"; } else { printf "Table: ".$table." does not exist creating: ".$table."\n"; $checkExist = $dbh->prepare("CREATE TABLE IF NOT EXISTS `".$table."` ( `id` int(11) NOT NULL AUTO_INCREMENT, `UnixTime` int(11) NOT NULL, `losses` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;"); if (!$checkExist->execute()) { die "Error: ". $checkExist->errstr ."\n"; } $checkExist->finish(); $dbh->disconnect(); } # End of else my $range = 50; my $minimum = 100; my $random_number = int(rand($range)) + $minimum; my $time = time(); my $losses = $time . ' ' . $random_number; $dbh = DBI->connect("dbi:mysql:".$db.":".$host.":".$port."", "".$user."", "".$pass."", { 'PrintError' => 1, 'RaiseError' => 1 } ) or die "Could not connect to ".$host.": ". $DBI::errstr ."\n"; $checkExist = $dbh->prepare("INSERT IGNORE INTO `".$table."` (`UnixTime`, `losses`) VALUES ('".$time."','".$random_number."') "); if (!$checkExist->execute()) { die "Error: ". $checkExist->errstr ."\n"; } $checkExist->finish(); $dbh->disconnect(); return $losses; } # End of mysql sub my $output = &mysql(); print "Added:" .$output. "\n";