繁体   English   中英

使用Perl DBI模块的语法错误

[英]Syntax error using Perl DBI module

我正在编写Perl代码,并在扩展名为.pm的文件中使用DBI模块。

导入DBI模块时,出现类似以下错误

syntax error at /etc/perl/Foo.pm line 13, near "DBI:"
Compilation failed in require at join.pl

join.pl文件中,我们将模块Foo.pm称为

use Foo;
Foo::dbconnect();

Foo.pm的代码是这样的

#!/usr/bin/perl

package Foo;

use DBI;

sub dbconnect {
  my $database = "DB_NAME";
  my $user ="user_name";
  my $password = "password";
  my $dsn = "dbi:mysql:$database:localhost:3306";
  my $connect = DBI:connect->($dsn, $user, $password)
      or die "can't connect to the db   $DBI::errstr\n";
  return $connect;
}

1;

我在一行中得到错误

my $connect = DBI:connect->($dsn, $user, $password)
    or die "can't connect to the db   $DBI::errstr\n";

请帮我解决这个问题。

欢迎来到SO。

首先,您应该始终use strictuse warnings来帮助发现代码中的问题。

您的connect线路中存在语法错误。 尝试这个:

my $connect = DBI->connect($dsn, $user, $password) 
    or die "can't connect to the db $DBI::errstr\n";

忠告:建议以变量代表的名称命名。 我建议使用$dbh代替$connect作为数据库句柄 ,但这当然取决于首选项。

connect方法DBI:connect->(...)使用的语法错误。

如果您使用两个冒号而不是一个并删除了箭头,那将是有效的语法,但是它仍然无法正常工作。

您需要的是一个类方法调用,像这样

my $connect = DBI->connect($dsn, $user, $password)
    or die "can't connect to the db: $DBI::errstr\n";

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM