Search code examples
mysqldbiraku

How to connect to local MySQL Server 8.0 with DBIish in Perl6


I'm working on a Perl6 project, but having difficulty connecting to MySQL. Even when using the DBIish (or perl6.org tutorial) example code, the connection fails. Any suggestions or advice is appreciated! User credentials have been confirmed accurate too.

I'm running this on Windows 10 with MySQL Server 8.0 and standard Perl6 with Rakudo Star. I have tried modifying the connection string in numerous ways like :$password :password<> :password() etc. but can't get a connection established. Also should note that I have the ODBC, C, C++, and.Net connectors installed.

#!/usr/bin/perl6
use v6.c;
use lib 'lib';
use DBIish;
use Register::User;

# Windows support
%*ENV<DBIISH_MYSQL_LIB> = "C:/Program Files/MySQL/MySQL Server 8.0/liblibmysql.dll"
    if $*DISTRO.is-win;

my $dbh = DBIish.connect('mysql', :host<localhost>, :port(3306), :database<dbNameHere>, :user<usernameHere>, :password<pwdIsHere>) or die "couldn't connect to database"; 
my $sth = $dbh.prepare(q:to/STATEMENT/);
    SELECT *
    FROM users
    STATEMENT

$sth.execute();

my @rows = $sth.allrows();

for @rows { .print }
say @rows.elems;

$sth.finish;
$dbh.dispose;

This should be connecting to the DB. Then the app runs a query, followed by printing out each resulting row. What actually happens is the application hits the 'die' message every time.


Solution

  • This is more of a work around, but being unable to use use a DB is crippling. So even when trying to use the NativeLibs I couldn't get a connection via DBIish. Instead I have opted to using DB::MySQL which is proving to be quite helpful. With a few lines of code this module has your DB needs covered:

    use DB::MySQL;
    
    my $mysql = DB::MySQL.new(:database<databaseName>, :user<userName>, :password<passwordHere>);
    my @users = $mysql.query('select * from users').arrays;
    
    for @users { say "user #$_[0]: $_[1] $_[2]"; }
    
    #Results would be:
    #user #1: FirstName LastName
    #user #2: FirstName LastName
    #etc...
    

    This will print out a line for each user formatted as shown above. It's not as familiar as DBIish, but this module gets the job done as needed. There's plenty more you can do with it to, so I highly recommend reading the docs.