How to access MySQL database using Perl

How to access MySQL database using Perl

To access a MySQL database from a Perl script, you need to use a MySQL database driver for Perl. One of the most popular MySQL database drivers for Perl is DBI (Database Independent Interface for Perl).

Here is a basic example of how to use DBI to connect to a MySQL database and execute a simple query:

refer‮ot ‬:lautturi.com
use DBI;

# Connect to the database
my $dbh = DBI->connect("DBI:mysql:database=mydatabase;host=localhost", "username", "password", {'RaiseError' => 1});

# Prepare and execute the query
my $sth = $dbh->prepare("SELECT * FROM users");
$sth->execute();

# Fetch the results
while (my $row = $sth->fetchrow_hashref()) {
   print "Username: $row->{username}\n";
   print "Email: $row->{email}\n";
}

# Disconnect from the database
$dbh->disconnect();

This example connects to a MySQL database named "mydatabase" running on localhost, using the "username" and "password" for authentication. It then prepares and executes a SELECT query to retrieve all rows from the "users" table. The results are then fetched and printed to the screen.

For more information on how to use DBI to access MySQL databases from Perl, consult the DBI documentation and online resources available. There are also many other MySQL database drivers for Perl available, each with its own set of features and capabilities. Consult the documentation and online resources available for more information on these drivers and how to use them.

Created Time:2017-10-28 21:38:57  Author:lautturi