3. 使用Perl连接DB2
(1)使用DBI函数DBI->data_sources 来扫描DB2数据库目录并返回一个包含了有效数据源名称(DSN)的数组。
----------------datasources.pl-------------
#!/usr/lib/perl -w
#
# This perl script prints the list of cataloged DB2 data-sources
#
use DBI;
use DBD::DB2;
use DBD::DB2::Constants;
print "Operating Systems = $^O\n";
print "Perl Binary = $^X\n";
print "Perl Version = $]\n";
print "DBI Version = $DBI::VERSION\n";
print "DBD::DB2 Version = $DBD::DB2::VERSION\n\n";
(2)获取db2数据库的信息
----------datasourceInfo.pl--------------------------
#!/usr/lib/perl -w
#
# This perl script prints the information DB2 database
#
use DBI;
use DBD::DB2;
use DBD::DB2::Constants;
my $dsn = 'dbi:DB2:SAMPLE';
my $uid = 'henry';
my $pwd = 'happyday';
my $dbh = DBI->connect( $dsn, $uid, $pwd ) || die "$DBI::errstr";
(3)获取db2数据库的元数据(比如, 表结构)
----------tableinfo.pl--------------------------
#!/usr/lib/perl -w
#
# This perl script prints the information of cataloged DB2 table
#
use DBI;
use DBD::DB2;
use DBD::DB2::Constants;
# Now get the column information for this table
$sth_col = $dbh->column_info( $catalog, $schema, $table, '%' );
if( $sth_col )
{
while( @row_col = $sth_col->fetchrow_array )
{
# @row_col has a lot more information. I'll just take
# these three fields as an example
$column_name = $row_col[3];
$type_name = $row_col[5];
$column_size = $row_col[6];
(4)执行SQL
----------executesql.pl--------------------------
#!/usr/lib/perl -w
#
# This perl script manipulate DB2 table
#
use DBI;
use DBD::DB2;
use DBD::DB2::Constants;