You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

传递参数后无法连接DB2数据库,报Invalid argument value错误

Perl脚本连接DB2问题修复

核心问题与修复方案

1. 配置文件读取失败(仅读到空格)

原脚本中配置文件的匹配正则存在错误:

if ($line =~  /^(\w+)\s\*=\s*(.*)$/) {

这里的\*会强制匹配星号,但正常配置行格式是key=value,并无星号。修改正则,去掉多余的星号转义,同时优化空格匹配逻辑:

if ($line =~ /^(\w+)\s*=\s*(.*)$/) {
  • \s*表示匹配0个或多个空格,兼容key=value、key = value等多种格式
  • 移除\*后,才能正确识别=分隔的键值对

2. DB2连接失败(invalid argument value)

原DBI连接字符串存在多余空格:

my $dbh = DBI->connect("DBI: DB2: $name", "$user", "$password") 

DBI的DSN格式要求严格,DBI:与驱动名DB2之间不能有空格,否则会被解析为无效参数。修改为:

my $dbh = DBI->connect("DBI:DB2:$name", $user, $password) 
  or die "Cannot connect to DB: " . DBI->errstr;
  • 移除DBI:后的空格,符合DBI:driver:database的标准格式
  • 追加DBI->errstr可打印具体错误信息,方便排查问题

3. 其他语法与逻辑修复

  • print语句语法错误:原代码中$name后缺少连接运算符.,导致编译报错,修改为:
    print $user . "\n" . $name . "\n" . $password . "\n";
    
  • 命令行参数提示错误:原die信息描述不清,修改为明确的用法提示:
    die "Usage: $0 <config file> <details file>\n";
    

完整修复后的脚本

#!/usr/bin/perl -w

use warnings;
use strict;

use DBI;

sub routine {
  my (%data) = @_;

  my $user = $data{'db2_user'};
  my $name = $data{'db2_name'};
  my $password = $data{'db2_passwd'};

  print $user . "\n" . $name . "\n" . $password . "\n";

  my $dbh = DBI->connect("DBI:DB2:$name", $user, $password) 
    or die "Cannot connect to DB: " . DBI->errstr;

  # 后续数据库操作...
  $dbh->disconnect;
}

# Main function
my ($config_file, $details_file);

# Check number of argument on command line
if (@ARGV == 2) {
  $config_file = $ARGV[0];
  $details_file = $ARGV[1];
}
else {
  die "Usage: $0 <config file> <details file>\n";
}

open (my $input_fh, "<", $details_file)
  or die "Cannot open details file: $!";

my %data;

while (my $line = <$input_fh>) {
  chomp $line;
  # 匹配key=value格式,兼容前后空格
  if ($line =~ /^(\w+)\s*=\s*(.*)$/) {
    $data{$1} = $2;
  }
}

close $input_fh;

routine(%data);

exit 0;

内容的提问来源于stack exchange,提问作者Coder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 23:27:19