Perl DBI Connection Inconsistencies

时间:2015-06-25 19:09:36

标签: mysql sql-server database perl dsn

Background I am working on a project than involves the retrieval of data from two difference databases. One of the databases is using a Microsoft SQL database engine and the other is running a MySQL engine. I need an easy way to specify the Data Source Name (DSN) from a configuration perspective, but due to inconsistencies in the DSN naming conventions, this is not possible with theDBI module (from what I have experienced). MySQL Consider the following connection: my $dsn = "dbi:mysql:host=$host;database=$db_name"; my $dbh = DBI->connect($dsn, $user, $pass); Assuming the supplied database name exists at the host, this connection will be succesful. I have tested this many times. Feel free to verify this yourself. MS SQL Now I try to connect to a Microsoft SQL server using the same DSN connection string format, with the exception of the database driver type. my $dsn = "dbi:odbc:host=$host;database=$db_name"; my $dbh = DBI->connect($dsn, $user, $pass); Even if the database exists on the supplied host, this connection fails, and the error message is like that shown below: DBI connect('host=$host;database=$db_name','$user',...) failed: (mtodbc): Fetching info: [unixODBC][Driver Manager]Connnection does not exist (SQLSTATE:08003) (CODE:0) (SEVERITY:SQLException) DBD: [dbd_db_login6/checkOutConnectionW(login)] RetCode=[-1] at perl_script.pl line X The DBI module is a database independent interface for Perl, yet clearly this problem is database dependent.. This seems like a bad design decision. Am I missing something? If so, please provide some reasoning why this design was done in this way.

2 个答案:

答案 0 :(得分:4)

在Windows中,您可以使用:

DBI->connect('dbi:ODBC:driver={SQL Server};database=catalog;Server=server\\instance;',$user,$password);

其中:

  • server是mssql server的ip地址
  • instance是实例名称
  • catalog是数据库名称

在linux / unix中我建议freetds

来自DBI documentation

Connect

$dbh = DBI->connect($data_source, $username, $password)
          or die $DBI::errstr;
$dbh = DBI->connect($data_source, $username, $password, \%attr)
          or die $DBI::errstr;

$ data_source值的示例是:

dbi:DriverName:database_name
dbi:DriverName:database_name@hostname:port
dbi:DriverName:database=database_name;host=hostname;port=port
  

驱动程序名称后面的文本没有标准。每   驱动程序可以自由使用它想要的任何语法。唯一的要求   DBI提出的是所有信息都是一次性提供的   串。您必须查阅您所在司机的文档   用于描述他们需要的语法。

     

建议驱动程序支持ODBC样式,如图所示   上面的例子。还建议他们支持这三者   常用名称'host','port'和'database'(加'db'作为别名   数据库)。这简化了基本DSN的自动构建:   “DBI:$驱动程序:数据库= $分贝;主机= $主机;端口= $端口”即可。司机应该瞄准   在给出这种形式的DSN时“做一些合理的事情”,但如果有的话   对于那个驱动程序(例如Informix的'port'),part是没有意义的   如果该部分不为空,则应该生成错误。

答案 1 :(得分:1)

驾驶员所需的参数因驾驶员而异。 DBD :: ODBC文档中的示例是

DBI->connect('dbi:ODBC:DSN=mydsn', $user, $pass)

根据评论中发布的链接,似乎可以将上述内容缩短为

DBI->connect('dbi:ODBC:mydsn', $user, $pass)

没有关于其他参数被接受的可能性的信息(例如,指定文件DSN或内联DSN的方法)。