perl - 操作数据库

[b]插入DB[/b]
use strict;
use DBI;
use DBD::Oracle;

my $dbh=DBI->connect('DBI:Oracle:host=localhost;SID=XE','tristan','654321',{PrintError=>1,RaiseError=>1,ora_session_mode=>2});

my $sql = qq{ CREATE TABLE tristan.employees ( id INTEGER NOT NULL,
name VARCHAR2(128),
title VARCHAR2(128),
phone CHAR(8)
) };
$dbh->do( $sql );

$dbh->disconnect();


[b]访问数据库的代码[/b]
use strict;
use DBI;
use DBD::Oracle;

my $dbh=DBI->connect('DBI:Oracle:host=localhost;SID=XE','tristan','654321',{PrintError=>1,RaiseError=>1,ora_session_mode=>2});

my $sql = "select accout_no, cust_name from tristan.tbl_cust_info";
my $sth = $dbh->prepare($sql);
$sth->execute();

#my( $a, $b);
#$sth->bind_columns( \$a, \$b);
#while($sth->fetchrow()) {
# print "$a, $b\n";
#}

my @row;
while(@row=$sth->fetchrow_array()) {
print "$row[0], $row[1]\n";
}

$sth->finish();
$dbh->disconnect();



[b]插入DB[/b]

#!c:/perl/bin/perl -X
use DBI;
use DBD::Oracle;

my $dbh=DBI->connect('DBI:Oracle:host=localhost;SID=XE','tristan','654321',{RaiseError=>1, AutoCommit => 0});

my @records = (
[ 0, "Larry Wall", "Perl Author", "555-0101" ],
[ 12, "Tim Bunce", "DBI Author", "555-0202" ],
[ 2, "Randal Schwartz", "Guy at Large", "555-0303" ],
[ 3, "Doug MacEachern", "Apache Man", "555-0404" ]
);

my $sql = qq{ INSERT INTO tristan.employees VALUES ( ?, ?, ?, ? ) };
my $sth = $dbh->prepare( $sql );

for( @records ) {
eval {
$sth->bind_param( 1, @$_->[0], { TYPE => SQL_INTEGER } );
$sth->bind_param( 2, @$_->[1], { TYPE => SQL_VARCHAR } );
$sth->bind_param( 3, @$_->[2], { TYPE => SQL_VARCHAR } );
$sth->bind_param( 4, @$_->[3], { TYPE => SQL_VARCHAR } );
$sth->execute();
$dbh->commit();
};

if( $@ ) {
warn "Database error: $DBI::errstr\n";
$dbh->rollback(); #just die if rollback is failing
}
}

$sth->finish();
$dbh->disconnect();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值