Skip to content

Instantly share code, notes, and snippets.

@rwp0
Last active July 5, 2022 12:17
Show Gist options
  • Save rwp0/d985bd713469f5fbc1131487f0383df4 to your computer and use it in GitHub Desktop.
Save rwp0/d985bd713469f5fbc1131487f0383df4 to your computer and use it in GitHub Desktop.
Perl DBI in Five Steps
#! /usr/bin/env perl
use v5.32;
use warnings;
use DBD::mysql;
my %mysql = (
host => 'example.com',
port => 3306,
database => 'example_database',
user => 'example_user',
password => 'example_password',
);
$mysql{ dsn } = "dbi:mysql:database=$mysql{database};host=$mysql{host};port=$mysql{port}";
my $dbi = DBI -> connect(
$mysql{dsn},
$mysql{user},
$mysql{password},
{
RaiseError => 1, # Frees from $DBI::errstr, and the errstr method
PrintError => 0,
}
); # return value: DBI::db
my $sql = $dbi -> prepare( <<~ "SQL" ); # return value: DBI::st
SELECT servers.server
FROM servers
JOIN inventory
ON inventory.field = 'server'
AND inventory.deleted IS NULL
AND inventory.provisioned = servers.id
WHERE dedicated
AND NOT shared
AND system = ?
ORDER BY servers.server
SQL
# system 0 is Unix, system 1 is Windows
$sql -> bind_param( 1, $ARGV[0] eq 'windows' ? 1 : 0 );
$sql -> execute;
my @servers;
my $server;
while ( my $row = $sql -> fetch ) {
$server = $row -> [0];
push @servers, $server;
}
say for
sort { substr( $a, 3 ) <=> substr( $b, 3 ) }
@servers;
@rwp0
Copy link
Author

rwp0 commented Jul 5, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment