设置 Perl DBI 连接属性

Perl DBI 模块包含一些属性,您可以使用这些属性控制其数据库连接的行为。这些属性与 ODBC 连接参数相似(在某些情况下,它们复制彼此的功能)。DBI 连接属性是一种用于控制数据库连接的行为的跨平台方法。

可以在建立连接时通过向 DBI connect 函数传递包含属性/值对的哈希值来设置 DBI 连接属性。例如,若要将 DBI 连接属性 AutoCommit 设置为 false,您应使用以下语句:

# Create a hash that holds attributes for the connection
my $attr = {AutoCommit => 0};
# Open a connection using a DSN. Supply the username and password.
my $dbh = DBI->connect("dbi:ODBC:VerticaDSN","ExampleUser","password123",
    $attr);

有关可在数据库连接上设置的属性的完整描述,请参阅 DBI 文档的 Database Handle Attributes(“数据库句柄属性”)一节。

脚本已连接之后,它可以通过将数据库句柄用作哈希引用来访问和修改连接属性。例如:

print "The AutoCommit attribute is: " . $dbh->{AutoCommit} . "\n";

以下示例演示了设置两个连接属性:

  • RaiseError 控制 DBI 驱动程序是否在遇到数据库错误时生成 Perl 错误。通常,如果希望 Perl 脚本在遇到数据库错误时退出,您可以将此属性设置为 true (1)。

  • AutoCommit 控制语句是否在完成后自动提交其事务。DBI 默认设置为 Vertica 的 AutoCommit 默认值 (true)。批量加载数据时,始终应将 AutoCommit 设置为 false (0) 以提高数据库效率。

#!/usr/bin/perl
use strict;
use DBI;
# Create a hash that holds attributes for the connection
 my $attr = {
                RaiseError => 1, # Make database errors fatal to script
                AutoCommit => 0, # Prevent statements from committing
                                 # their transactions.
            };
# Open a connection using a DSN. Supply the username and password.
my $dbh = DBI->connect("dbi:ODBC:VerticaDSN","ExampleUser","password123",
    $attr);

if (defined $dbh->err) {
    # Connection failed.
    die "Failed to connect: $DBI::errstr";
}
print "Connected!\n";
# The database handle lets you access the connection attributes directly:
print "The AutoCommit attribute is: " . $dbh->{AutoCommit} . "\n";
print "The RaiseError attribute is: " . $dbh->{RaiseError} . "\n";
# And you can change values, too...
$dbh->{AutoCommit} = 1;
print "The AutoCommit attribute is now: " . $dbh->{AutoCommit} . "\n";
$dbh->disconnect();

运行该示例后,将输出以下内容:

Connected!The AutoCommit attribute is: 0
The RaiseError attribute is: 1
The AutoCommit attribute is now: 1