本文将提供一些perl连接Microsoft SQL Server数据库的实例。perl脚本运行在Windows和Linux平台。
Windows平台
如果在Windows平台下运行perl脚本,建议使用依赖DBI的两个模块包,提供标准的数据库接口模块。
DBD::ODBC
DBD::ADO
使用DBD::ODBC
如果选用DBD::ODBC,下面的实例代码将展示如何连接到SQL Server数据库:
代码如下:
use DBI;
# DBD::ODBC
my $dsn = 'DBI:ODBC:Driver={SQL Server}';
my $host = '10.0.0.1,1433';
my $database = 'my_database';
my $user = 'sa';
my $auth = ‘s3cr3t';
# Connect via DBD::ODBC by specifying the DSN dynamically.
my $dbh = DBI->connect("$dsn;Server=$host;Database=$database",
$user,
$auth,
{ RaiseError => 1, AutoCommit => 1}
) || die "Database connection not made: $DBI::errstr";
#Prepare a SQL statement my $sql = "SELECT id, name, phone_number FROM employees ";
my $sth = $dbh->prepare( $sql );
#Execute the statement
$sth->execute();
my( $id, $name, $phone_number );
# Bind the results to the local variables
$sth->bind_columns( undef, /$id, /$name, /$phone_number );
#Retrieve values from the result set
while( $sth->fetch() ) {
print "$id, $name, $phone_number/n";
}
#Close the connection
$sth->finish();
$dbh->disconnect();
你还可以使用预先设置的一个系统DSN来连接。要建立一个系统DSN,可以这样访问控制面板->管理工具->数据源。
使用系统DSN连接,需要更改连接字符串。如下所示:
代码如下:
# Connect via DBD::ODBC using a System DSN
my $dbh = DBI->connect("dbi:ODBC:my_system_dsn",
$user,
$auth,
{
RaiseError => 1,
AutoCommit => 1
}
) || die "Database connection not made: $DBI::errstr";
使用DBD::ADO
如果选择DBD::ADO模块,下面的实例展示如何连接到SQL Server数据库。
代码如下:
use DBI;
my $host = '10.0.0.1,1433';
my $database = 'my_database';
my $user = 'sa';
my $auth = ‘s3cr3t';
# DBD::ADO
$dsn = "Provider=sqloledb;Trusted Connection=yes;";
$dsn .= "Server=$host;Database=$database";
my $dbh = DBI->connect("dbi:ADO:$dsn",
$user,
$auth,
{ RaiseError => 1, AutoCommit => 1}
) || die "Database connection not made: $DBI::errstr";
#Prepare a SQL statement
my $sql = "SELECT id, name, phone_number FROM employees "; my $sth = $dbh->prepare( $sql );
#Execute the statement
$sth->execute();
新闻热点
疑难解答