Perl Database Connection
In this chapter, we will introduce database connections in Perl.
In Perl 5, we can use the DBI module to connect to a database.
DBI's full English name is Database Independent Interface.
As the standard interface for communicating with databases in Perl, DBI defines a series of methods, variables, and constants, providing a database persistence layer that is independent of any specific database platform.
DBI structure
DBI is independent of specific database platforms, so we can apply it to databases such as Oracle, MySQL, or Informix.

In the diagram, DBI receives all SQL data sent by APIs (Application Programming Interface), then distributes it to the corresponding drivers for execution, and finally retrieves and returns the data.
Variable naming conventions
The following sets up commonly used variable naming methods:
$dsn 驱动程序对象的句柄
$dbh 一个数据库对象的句柄
$sth 一个语句或者一个查询对象的句柄
$h 通用的句柄 ($dbh, $sth, 或 $drh),依赖于上下文
$rc 操作代码返回的布什值(true 或 false)
$rv 操作代码返回的整数值
@ary 查询返回的一行值的数组(列表)
$rows 操作代码返回的行数值
$fh 文件句柄
undef NULL 值表示未定义
\%attr 引用属性的哈希值并传到方法上
Database connection
Next, we'll use the MySQL database as an example to demonstrate how Perl operates on databases.
Here we create the RUNOOB database in MySQL, with the data table named Websites; the table structure and data are shown below:

Download this data table:https://static.jyshare.com/download/websites_perl.sql
Next, we use the following code to connect to the database:
Example
#!/usr/bin/perl -w
use strict
;
use DBI
;
my
$host
=
"
localhost
"
;
Host address
my
$driver
=
"
mysql
"
;
Interface type, defaults to localhost
my
$database
=
"
RUNOOB
"
;
Database
The handle of the driver object
my
$dsn
=
"
DBI:
$driver
:database=
$database
:
$host
"
;
my
$userid
=
"
root
"
;
Database username
my
$password
=
"
123456
"
;
Database password
Connect to the database
my
$dbh
=
DBI
->
connect
(
$dsn
,
$userid
,
$password
)
or
die
$DBI::errstr
;
my
$sth
=
$dbh
->
prepare
(
"
SELECT * FROM Websites
"
)
;
Prepare the SQL statement
$sth
->
execute
(
)
;
Execute the SQL operation
Comment: this part uses bound values
$alexa = 20;
my $sth = $dbh->prepare("SELECT name, url
FROM Websites
WHERE alexa > ?");
$sth->execute( $alexa ) or die $DBI::errstr;
Loop to output all data
while
(
my
@row
=
$sth
->
fetchrow_array
(
)
)
{
join
(
'
\t
'
,
@row
)
.
"
\n
"
;
}
$sth
->
finish
(
)
;
$dbh
->
disconnect
(
)
;
Insertion operation
Execution steps:
- Use the prepare() API to preprocess the SQL statement.
- Use the execute() API to execute the SQL statement.
- Use the finish() API to release the statement handle.
- Finally, if everything goes well, the above operations are committed.
my $sth = $dbh->prepare("INSERT INTO Websites
(name, url, alexa, country )
values
('Twitter', 'https://twitter.com/', 10, 'USA')");
$sth->execute() or die $DBI::errstr;
$sth->finish();
$dbh->commit or die $DBI::errstr;
Applications can also bind output and input parameters. The following example executes an insert query by replacing the ? placeholder with a variable:
my $name = "Twitter";
my $url = "https://twitter.com/";
my $alexa = 10;
my $country = "USA";
my $sth = $dbh->prepare("INSERT INTO Websites
(name, url, alexa, country )
values
(?,?,?,?)");
$sth->execute($name,$url,$alexa, $country)
or die $DBI::errstr;
$sth->finish();
$dbh->commit or die $DBI::errstr;
Update operation
Execution steps:
- Use the prepare() API to preprocess the SQL statement.
- Use the execute() API to execute the SQL statement.
- Use the finish() API to release the statement handle.
- Finally, if everything goes well, the above operations are committed.
my $sth = $dbh->prepare("UPDATE Websites
SET alexa = alexa + 1
WHERE country = 'CN'");
$sth->execute() or die $DBI::errstr;
print "更新的记录数 :" + $sth->rows;
$sth->finish();
$dbh->commit or die $DBI::errstr;
Applications can also bind output and input parameters. The following example executes an update query by replacing the ? placeholder with a variable:
$name = 'Runoob Tutorial';
my $sth = $dbh->prepare("UPDATE Websites
SET alexa = alexa + 1
WHERE name = ?");
$sth->execute('$name') or die $DBI::errstr;
print "更新的记录数 :" + $sth->rows;
$sth->finish();
Of course, we can also bind the values to be set. For example, the following changes the alexa of all rows where country is CN to 1000:
$country = 'CN';
$alexa = 1000:;
my $sth = $dbh->prepare("UPDATE Websites
SET alexa = ?
WHERE country = ?");
$sth->execute( $alexa, '$country') or die $DBI::errstr;
print "更新的记录数 :" + $sth->rows;
$sth->finish();
Delete data
Execution steps:
- Use the prepare() API to preprocess the SQL statement.
- Use the execute() API to execute the SQL statement.
- Use the finish() API to release the statement handle.
- Finally, if everything goes well, the above operations are committed.
The following deletes all data in Websites where alexa is greater than 1000:
$alexa = 1000;
my $sth = $dbh->prepare("DELETE FROM Websites
WHERE alexa = ?");
$sth->execute( $alexa ) or die $DBI::errstr;
print "删除的记录数 :" + $sth->rows;
$sth->finish();
$dbh->commit or die $DBI::errstr;
Using the do statement
do The statement can execute UPDATE, INSERT, or DELETE operations; it is relatively short to use, returns true on success, and returns false on failure. Example below:
$dbh->do('DELETE FROM Websites WHERE alexa>1000');
COMMIT operation
commit submits a transaction, completing the database operation:
$dbh->commit or die $dbh->errstr;
ROLLBACK operation
If an error occurs during SQL execution, the data can be rolled back without making any changes:
$dbh->rollback or die $dbh->errstr;
Transactions
Like other languages, Perl DBI also supports transaction processing for database operations, in two ways:
1. Start a transaction when connecting to the database
$dbh = DBI->connect($dsn, $userid, $password, {AutoCommit => 0}) or die $DBI::errstr;
The above code sets AutoCommit to false when connecting, which means that when you perform an update operation on the database, it does not automatically write those updates directly to the database. Instead, the program must call $dbh->commit to actually write the data to the database, or $dbh->rollback to roll back the operation.
2. Start a transaction through the $dbh->begin_work() statement
This way, there is no need to set AutoCommit = 0 when connecting to the database.
Multiple transaction operations can be performed in a single database connection, without needing to connect to the database again at the start of each transaction.
$rc = $dbh->begin_work or die $dbh->errstr;
#####################
##这里执行一些 SQL 操作
#####################
$dbh->commit; # 成功后操作
-----------------------------
$dbh->rollback; # 失败后回滚
Disconnecting from the database
If we need to disconnect from the database, we can use the disconnect API:
$rc = $dbh->disconnect or warn $dbh->errstr;