如何使用perl连接SQL Server

时间:2009-12-23 00:15:11

标签: sql-server activeperl

我知道有一个类似的问题:Connect to SQL Server 2005 from Perl and do a SELECT,但我尝试了接受的答案而无法让它发挥作用。

假设我有一个名为test的db,并且很乐意从mytable中选择 (select id, name from mytable

代码来自上面的链接,更新了dsn:

use strict;
use warnings;
use DBI;

# Insert your DSN's name here.
my $dsn = 'database=test'

# Change username and password to something more meaningful
my $dbh = DBI->connect("DBI::ODBC::$dsn", 'username', 'password')

# Prepare your sql statement (perldoc DBI for much more info).
my $sth = $dbh->prepare('select id, name from mytable');

# Execute the statement.
if ($sth->execute)
{
    # This will keep returning until you run out of rows.
    while (my $row = $sth->fetchrow_hashref)
    {
        print "ID = $row->{id}, Name = $row->{name}\n";
    }
}

# Done. Close the connection.
$dbh->disconnect;

这是我在运行脚本时得到的: 无法连接到数据源'ODBC :: database = test'因为我无法解决什么问题  要使用的驱动程序(它似乎不包含'dbi:driver:'前缀和DBI_DR 在script.pl第9行没有设置IVER env var

看起来问题出现在dsn中,但我不知道如何修复它(我在sql 2005上,主动perl 5.10和windows xp)。

编辑: 我使用以下代码来验证是否已安装ODBC。     使用DBI;

print join (", ", DBI->installed_versions);

输出: 看起来ODBC确实在列表中。

ADO, CSV, DBM, ExampleP, File, Gofer, ODBC, SQLite, Sponge, mysql

我错过了什么?

3 个答案:

答案 0 :(得分:2)

我刚才和SQLite有同样的错误,看起来你做的和我一样错了。请注意第一个参数中的冒号数量 - 这是错误的格式:

my $db = DBI->connect('DBI::SQLite::dbname=testing.db', '', '', {RaiseError => 1, AutoCommit => 1});

在第一个参数中实际上应该只有两个冒号,而不是两对冒号:

my $db = DBI->connect('DBI:SQLite:dbname=testing.db', '', '', {RaiseError => 1, AutoCommit => 1});

问题尽管年龄已经回答,但因为 <=> Google

答案 1 :(得分:0)

尝试将DSN设置为:

my $dbh = DBI->connect("dbi:ODBC:test", 'username', 'password')

如果这不起作用,请确保通过运行:

安装了DBD :: ODBC
perl -MDBI -e 'DBI->installed_versions;'

答案 2 :(得分:0)

假设SQL服务器位于本地服务器上,下面的连接可以是正确的:

my $DSN = "driver={SQL Server};Server=127.0.0.1;Database=test;UID=sa;PWD=123456";
my $dbh = DBI->connect("dbi:ODBC:$DSN");
相关问题