execute()
$sth->execute([@values])
This function executes a statement handle that has been
processed with the prepare() method. A value
of undef is returned if there’s an error. It
returns true if successful, even when the results set is blank or
zero. For statements other than SELECT statements,
the number of rows affected is returned. Here is an example:
...
my $dbh = DBI->connect ("$data_source","$user","$pwd")
my $pub_year = '1961';
my $genre = 'novel';
my $sql_stmnt = "SELECT title, author
FROM books
WHERE pub_year = '$pub_year'
AND genre = '$genre'";
my $sth = $dbh->prepare($sql_stmnt);
my $rows_chg = $sth->execute();
while( my($title,$author) = $sth->fetchrow_array()) {
print "$title by $author \n";
}You can use placeholders in the SQL statement (e.g., for
$pub_year and $genre) by giving
the values with execute():
. . .
my @values = ('1961','novel');
my $sql_stmnt = "SELECT title, author
FROM books
WHERE pub_year = ?
AND genre = ?";
my $sth = $dbh->prepare($sql_stmnt);
$sth->execute(@values);
while( my($title,$author) = $sth->fetchrow_array()) {
print "$title by $author \n";
}You don’t have to put values into an array for use with this
method. You can put the strings inside the parentheses of the function
(e.g., $sth->execute($pub_year,$genre);).