Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Why was it neccessary to pass a DBI handler by reference?

by Anonymous Monk
on Jan 30, 2004 at 18:40 UTC ( [id://325332]=note: print w/replies, xml ) Need Help??


in reply to Why was it neccessary to pass a DBI handler by reference?

Following your description, I made an example to try to duplicate the behavior you were describing.

However, it does not do what you say. It seems to work fine.

#!/usr/bin/perl -w use DBI; use strict; package One; sub new { my $class = shift; my $self = bless {}, $class; my $dbh = shift || return undef; $self->{dbh} = $dbh; return $self; } sub execute { my $self = shift; my $query = shift; my $sth= $self->{dbh}->prepare($query); my $rows = $sth->execute or die $DBI::errstr;; print "$rows rows affected\n"; } sub begin_work{ my $self = shift; $self->{dbh}->begin_work; } sub commit{ my $self = shift; $self->{dbh}->commit; } package Two; sub new { my $class = shift; my $self = bless {}, $class; my $dbh = shift || return undef; $self->{dbh} = $dbh; return $self; } sub execute { my $self = shift; my $query = shift; my $sth= $self->{dbh}->prepare($query); my $rows = $sth->execute or die $DBI::errstr;; print "$rows rows affected\n"; } package main; my $dbh= DBI->connect("dbi:SQLite:dbname","","",{RaiseError => 1,AutoC +ommit=>1}) #my $dbh = DBI->connect("DBI:mysql:dbname", # 'user', 'password', {RaiseError => 1, AutoCommit=>1}) or die "can't connect\n"; $dbh->do(qq{delete from table1 where t2id =5}); $dbh->do(qq{delete from table2 where t2id =5}); my $query = qq{ insert into table1 values (5,"xxx") }; my $one = new One $dbh or die "can't create One\n"; my $two = new Two $dbh or die "can't create Two\n"; $one->begin_work(); # transaction starts in module One $one->execute($query); # transaction continues in module One $query = qq{insert into table2 values(11,"yyy", 5)}; $two->execute($query); # transaction continues in module Two $one->commit(); # transaction ends in module One $dbh->disconnect();

I tried this example with two different DBD drivers (MySQL and SQLite) and it worked as I expected. The transaction is processed correctly. Try to add a call to $dbh->rollback() after the first execute, and it will cancel the insertion without problems. It means that the transaction is really split across packages.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://325332]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (2)
As of 2024-04-25 19:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found