dbi beginner

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 UPDATE SQL 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

  • DBI is stable and consistent in Perl 5.8+ and later.
  • Always check for undef returns to catch errors.
  • Use RaiseError or manual error checking to handle failures gracefully.
  • Remember that UPDATE returns 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

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
Rows updated: 1
Bob's new age: 26
STDERR
(empty)

Was this helpful?

Related Questions