Accessing Microsoft SQL Server from Windows in PERL

五迷三道 提交于 2019-12-07 12:25:24

问题


I am using SQL Server driver. But this is the following error I get:

DBI connect('Driver={SQL Server}:$database:$host','cartertest',...) failed:
[Microsoft][ODBC Driver Manager] Invalid connection string attribute (SQL-01S00)
at PERL_SQL_Connect.pl line 15
Can't call method "disconnect" on an undefined value at PERL_SQL_Connect.pl line 16

This is my code:

use DBI;
use DBD::ODBC;
#my $dsn = "dbi:SQL Server:$database:$host";
my $dsn = 'DBI:ODBC:Driver={SQL Server}:$database:$host';

my $host = 'amber';    ##This is the server name
my $database = 'assignmentdb';     ##This is the database name
my $user = 'something';         ## Database User Name
my $auth = "something";

#my $dsn = "dbi:SQL Server:$database:$host";

$dbiconnect = DBI->connect($dsn,$user,$auth);   #line 15
$dbiconnect->disconnect();                      #line 16

What mistake(s) am I making?


回答1:


You can try this:

use DBI;

my $host     = 'amber';
my $database = 'assignmentdb';
my $user     = 'something';
my $auth     = 'something';

my $dsn = "dbi:ODBC:Driver={SQL Server};Server=$host;Database=$database";
my $dbh = DBI->connect($dsn, $user, $auth, { RaiseError => 1 });

# .... work with the handle

$dbh->disconnect;

Note that '' string does not interpolate your variables, so in your example $dsn string contains verbatim $database or $host, not their contents.




回答2:


Firstly add use strict and use warnings as you are referencing $database and $host before they are declared and assigned anything. However, as you used ' instead of " in this case strict would not have picked up the issue you have on line 4. Then move the other declarations before the declaration of $dsn. Remove 'use DBD::ODBC' as it does nothing in this case. Lastly read up about ODBC connection strings (see the DBD::ODBC FAQ for references). You cannot put a bare database name and host in the connection string. The string required is 'dbi:ODBC:attr1=value1;attr2=value2' where the attributes are partly defined by ODBC and partly by the ODBC Driver. bvr's example above shows that.



来源:https://stackoverflow.com/questions/6983586/accessing-microsoft-sql-server-from-windows-in-perl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!