To work with MySQL from Perl scripts, the DBI module is usually used. This allows you to conveniently open and close connections to the DBMS, prepare and execute queries to the database, handle errors, and so on. If you have no experience with MySQL from Perl.

So, an example of working with MySQL from Perl DBI:

#!/usr/bin/perl

use DBI;

my $host = "localhost"; # MySQL-server
my $port = "3306"; #port to which we open the connection
my $user = "u12345"; # username (randomly)
my $pass = "password"; # password
my $db = $user; # database name - by default equal to user name

print "Content-type: text/html\n\n";

$dbh = DBI->connect("DBI:mysql:$db:$host:$port",$user,$pass);
$sth = $dbh->prepare("select field1 from table2");# prepare the request
$sth->execute; # execute the request

while ($ref = $sth->fetchrow_arrayref) {
print "$$ref[0]\n"; # result
}

$rc = $sth->finish;    # close
$rc = $dbh->disconnect;  # connection

In this example, we first define variables with MySQL access parameters, then issue an HTTP header, since this is a script to run via the web, then connect to the database, prepare and send a select query, receive and print the results, and then close compound. This is the simplest script for working with MySQL from Perl.

Var dette svaret til hjelp? 74 brukere syntes dette svaret var til hjelp (228 Stemmer)