2

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

假设我有一个名为 test 的数据库,并且很想从 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 IVER env var)在 script.pl 第 9 行

看起来问题出在 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

我错过了什么?

4

3 回答 3

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});

尽管它的年龄已回答问题,因为它仍然是谷歌针对此特定错误消息的结果的顶部

于 2012-04-28T01:26:56.970 回答
0

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

my $DSN = "driver={SQL Server};Server=127.0.0.1;Database=test;UID=sa;PWD=123456";
my $dbh = DBI->connect("dbi:ODBC:$DSN");
于 2013-10-17T09:44:11.507 回答
0

尝试将您的 DSN 设置为:

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

如果这不起作用,请确保通过运行以下命令安装了 DBD::ODBC:

perl -MDBI -e 'DBI->installed_versions;'
于 2009-12-23T00:51:59.703 回答