How to execute UPDATE queries with Perl DBI?
Question
How to execute UPDATE queries with Perl DBI?
When working with databases in Perl, the DBI module is the standard interface for interacting with relational databases. If you want to execute an UPDATE SQL query—used to modify existing data—you can do so easily with DBI using the do method or by preparing and executing a statement handle.
Basic Steps to Execute an UPDATE Query Using DBI
- Connect to your database with
DBI->connect()>. - Prepare your
UPDATESQL statement optionally using placeholders (question marks) for parameters. - Execute the statement with the parameters.
- Check the number of affected rows.
- Disconnect when done.
Perl DBI Concepts to Know
DBI->connect()> returns a database handle (dbh) which you use for queries.- Preparing a statement returns a statement handle (sth), allowing you to execute the query multiple times with different parameters.
- Placeholders (
?) help avoid SQL injection and simplify statement execution with variables. $sth->execute(@bind_values)runs the query with those values substituted safely.
Version and Gotchas
DBIis stable and consistent in Perl 5.8+ and later.- Always check for
undefreturns to catch errors. - Use
RaiseErroror manual error checking to handle failures gracefully. - Remember that
UPDATEreturns the number of rows changed, which can be zero if no rows match. - Beware of quoting issues—placeholders handle this safely.
Runnable Example
use strict;
use warnings;
use DBI;
# Example uses SQLite in-memory database for demonstration,
# since it requires no setup or external access.
my $dsn = "dbi:SQLite:dbname=:memory:";
my $user = "";
my $password = "";
# Connect with RaiseError to die on error automatically
my $dbh = DBI->connect($dsn, $user, $password, { RaiseError => 1, AutoCommit => 1 });
# Create test table
$dbh->do('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)');
# Insert some initial data
$dbh->do('INSERT INTO users (name, age) VALUES (?, ?)', undef, 'Alice', 30);
$dbh->do('INSERT INTO users (name, age) VALUES (?, ?)', undef, 'Bob', 25);
# Now prepare an UPDATE statement with placeholders
my $sql = 'UPDATE users SET age = ? WHERE name = ?';
my $sth = $dbh->prepare($sql);
# Execute the UPDATE to change Bob's age to 26
my $rows_updated = $sth->execute(26, 'Bob');
print "Rows updated: $rows_updated\n";
# Verify update
my $new_age = $dbh->selectrow_array('SELECT age FROM users WHERE name = ?', undef, 'Bob');
print "Bob's new age: $new_age\n";
# Clean up
$sth->finish;
$dbh->disconnect;
Output:
Rows updated: 1 Bob's new age: 26
This example demonstrates a typical UPDATE use case:
- Connect to the database (SQLite in-memory for ease).
- Create table and insert data.
- Prepare and execute an UPDATE query with placeholders.
- Check how many rows were updated.
- Verify the change with a SELECT query.
Using prepare and execute is preferred for updates, especially if you run the same query many times with different values. For a quick, single update, $dbh->do($sql, undef, @bind_values) is a handy shortcut:
my $rows = $dbh->do('UPDATE users SET age = ? WHERE name = ?', undef, 27, 'Alice');
print "Updated $rows row(s)\n";
That said, prepared statements are better if you repeat the query multiple times, improving efficiency and safety.
Summary: With Perl DBI, execute UPDATE queries by preparing the statement with placeholders, then calling execute with the actual values. Always check the return value to see how many rows were affected, and leverage RaiseError or error handling to catch issues early.
Verified Code
Executed in a sandbox to capture real output. • v5.34.1 • 38ms
Rows updated: 1
Bob's new age: 26
(empty)Was this helpful?
Related Questions
- How to fetch data as hash of hashes in Perl DBI?
- How to use Perl DBI with DBD::ODBC for SQL Server?
- How to handle database connection pooling in Perl DBI?
- How to use Perl DBI selectall_arrayref for fetching all data?
- How to get column names from a Perl DBI statement handle?
- How to execute DELETE queries with WHERE clause in Perl DBI?