Last active
July 5, 2022 12:17
-
-
Save rwp0/d985bd713469f5fbc1131487f0383df4 to your computer and use it in GitHub Desktop.
Perl DBI in Five Steps
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /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; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Embedded in Medium post:
https://rwp0.medium.com/perl-dbi-in-five-steps-29ba3811fc4c