学习Perl的人可能都会用到DBI。网上的例子的大多是MySQL的,这回给大家发一个PostgreSQL版的。(其实和DB关系不大,只是不同的DB会影响不同的系统内置常量)
以下是一个连接PostgreSQL的例子,展现了DBI的基本功能。仅供大家参考。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| use DBI;
$data_source = "dbi:Pg:database=xxx;host=xxx.xxx.xxx.xxx;port=5432"; $username = "usr"; $password = "pwd"; $dbh = DBI->connect( $data_source, $username, $password, { RaiseError => 1 } ) or die; $sth = $dbh->prepare("select * from mst_user"); $sth->execute();
$col_num = $sth->{NUM_OF_FIELDS};
@cols = @{$sth->{NAME}}; print join("\t",@cols),"\n"; while ( @row_ary = $sth->fetchrow_array ) { for($i=0; $i<$col_num; $i++){ my $len = length $cols[$i] ; printf "%-${len}s\t", $row_ary[$i]; } print "\n"; } $sth->finish; $dbh->disconnect();
|