簡體   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