Perl provides robust support for executing SQL queries through its powerful DBI (Database Interface) module. This guide will walk you through the process of performing SQL queries in Perl, from connecting to a database to retrieving and manipulating data.
Before executing SQL queries, you need to establish a connection to your database. Here's a basic example:
use DBI;
my $dbh = DBI->connect("DBI:mysql:database=mydb;host=localhost", "username", "password")
or die "Couldn't connect to database: " . DBI->errstr;
This code snippet connects to a MySQL database named "mydb" on the local machine. Adjust the connection string, username, and password according to your database setup.
Once connected, you can execute SQL queries using the do()
method for non-SELECT queries or prepare()
and execute()
methods for more complex operations.
my $rows_affected = $dbh->do("INSERT INTO users (name, email) VALUES ('John Doe', 'john@example.com')")
or die "Couldn't execute statement: " . $dbh->errstr;
print "Rows affected: $rows_affected\n";
my $sth = $dbh->prepare("SELECT * FROM users WHERE age > ?")
or die "Couldn't prepare statement: " . $dbh->errstr;
$sth->execute(18)
or die "Couldn't execute statement: " . $sth->errstr;
while (my @row = $sth->fetchrow_array()) {
print "Name: $row[0], Email: $row[1]\n";
}
Placeholders (?) in SQL queries help prevent SQL injection attacks and improve query performance. They're especially useful when dealing with user input:
my $sth = $dbh->prepare("INSERT INTO products (name, price) VALUES (?, ?)")
or die "Couldn't prepare statement: " . $dbh->errstr;
$sth->execute("Widget", 19.99)
or die "Couldn't execute statement: " . $sth->errstr;
Perl offers several methods to fetch query results:
fetchrow_array()
: Returns an array of column valuesfetchrow_hashref()
: Returns a hash reference with column names as keysfetchall_arrayref()
: Returns all rows as an array of arraysExample using fetchrow_hashref()
:
my $sth = $dbh->prepare("SELECT id, name, email FROM users")
or die "Couldn't prepare statement: " . $dbh->errstr;
$sth->execute()
or die "Couldn't execute statement: " . $sth->errstr;
while (my $row = $sth->fetchrow_hashref()) {
print "ID: $row->{id}, Name: $row->{name}, Email: $row->{email}\n";
}
Proper error handling is crucial when working with databases. Always check for errors after executing queries:
my $sth = $dbh->prepare("SELECT * FROM non_existent_table")
or die "Prepare failed: " . $dbh->errstr;
if (!$sth->execute()) {
warn "Execute failed: " . $sth->errstr;
} else {
# Process results
}
For operations that require multiple queries to be executed as a single unit, use transactions:
$dbh->{AutoCommit} = 0; # Turn off autocommit
eval {
$dbh->do("UPDATE accounts SET balance = balance - 100 WHERE id = 1");
$dbh->do("UPDATE accounts SET balance = balance + 100 WHERE id = 2");
$dbh->commit;
};
if ($@) {
warn "Transaction failed: $@";
$dbh->rollback;
}
By following these guidelines and utilizing Perl's DBI module effectively, you can create robust and efficient database-driven applications. Remember to consult the DBI module documentation for more advanced features and optimizations.