Perl - MySQL connection

Sample code for connecting to a MySQL database using Perl and simple queries.

The USERNAME, PASSWORD and DATABASE_NAME variables must be substituted with those supplied for your web hosting account.


  • #
    # Example Perl database.
    #
    # Please run:
    #
    #       man DBI
    #
    # To get learn more about Perl database access.
    
    use DBI;
    
    my $db_host = 'localhost';
    my $db_user = 'USERNAME';
    my $db_pass = 'PASSWORD';
    my $db_name = 'DATABASE_NAME';
    
    # Connect to a MySQL database.
    my $db = "dbi:mysql:dbname=${db_name};host=${db_host}";
    
    # Connect to database.
    $dbh = DBI->connect($db, $db_user, $db_pass,
                           { RaiseError => 1, AutoCommit => 0 }
           ) || die "Error connecting to the database: $DBI::errstr\n";
    
    # Our query.
    my $query = "SELECT something FROM sometable";
    
    # Run query.
    $ref = $dbh->selectcol_arrayref($query);
    
    # Print results.
    print join("\n", @$ref);
    
    # end