Perl MySQL更新数据
时间:2019-11-20 08:52:39 来源:igfitidea点击:
简介:在本教程中,我们将逐步向您展示如何使用Perl DBI更新MySQL表中的数据。
Perl MySQL更新数据步骤
要更新表中的数据,请使用UPDATE语句。
您使用以下步骤通过使用DBI更新MySQL表中的数据:
首先,使用connect()方法连接到MySQL数据库。
my $dbh = DBI->connect($dsn,$username,$password, \%attr);
接下来,构造一个UPDATE语句并将其传递给数据库句柄对象的prepare()方法以准备要执行的语句。
my $sql = "UPDATE table_name SET col_name = ? WHERE id=?"; my $sth = $dbh->prepare($sql);
然后,如果要将值从Perl程序传递到UPDATE语句,则将占位符(?)放在语句中,并使用语句句柄对象的bind_param()方法绑定相应的参数。
$sth->bind_param(1,$value); $sth->bind_param(2,$id);
之后,调用语句句柄对象的execute()方法执行查询。
$sth->execute();
最后,使用connector()方法从MySQL数据库断开连接。
$dbh->disconnect();
Perl MySQL更新数据示例
下面的示例使用链接ID 2更新链接表中的数据。
在更新数据之前,让我们首先检查链接表:
SELECT * FROM links;
请参阅以下程序:
#!/usr/bin/perl
use strict;
use warnings;
use v5.10; # for say() function
use DBI;
# MySQL database configurations
my $dsn = "DBI:mysql:perlmysqldb";
my $username = "root";
my $password = '';
say "Perl MySQL Update Data Demo";
# connect to MySQL database
my %attr = ( PrintError=>0, RaiseError=>1);
my $dbh = DBI->connect($dsn,$username,$password, \%attr);
# update statement
my $sql = "UPDATE links
SET title = ?,
url = ?,
target = ?
WHERE id = ?";
my $sth = $dbh->prepare($sql);
my $id = 2;
my $title = "Perl MySQL Update Data Tutorial";
my $url = "https://www.theitroad.local/perl-mysql/perl-mysql-update/";
my $target = "_self";
# bind the corresponding parameter
$sth->bind_param(1,$title);
$sth->bind_param(2,$url);
$sth->bind_param(3,$target);
$sth->bind_param(4,$id);
# execute the query
$sth->execute();
say "The record has been updated successfully!";
$sth->finish();
# disconnect from the MySQL database
$dbh->disconnect();
该程序的输出是:
Perl MySQL Update Data Demo The record has been updated successfully!
让我们再次查询链接表以验证更新。
SELECT * FROM links;
ID为2的链接记录已成功更改。
在本教程中,您学习了如何通过使用Perl DBI中准备好的语句来更新MySQL表中的数据。

