和其它的语言一样, perl DBI对数据库的操作也支持事务处理, 它的实现方式有两个:
一: 在连接数据库的时候就开始一个事务
$dbh = DBI->connect($dataSource, $user, $passwd, {AutoCommit => 0});
可以看到在连接的时候设置了AutoCommit为false, 也就是说当你对数据库进行更新操作的时候, 它不会自动地把那些更新直接写到数据库里, 而是要程序通过 $dbh->commit来使数据真正地写到数据库里, 或 $dbh->rollback 来回滚刚才的操作
二:通过$dbh->begin_work()语句来开始一个事务
这种方式就不需要在连接数据库的时候设置AutoCommit = 0了, 本人认为这种方式更好, 可以一次数据库连接进行多次事务操作, 不用每一次事务的开始都去连接一次数据库。
示例代码为:
$dbh = DBI->connect($dataSource, $user, $passwd, {RaiseError => 1});
$dbh->begin_work
eval {
foo(…) # do lots of work here
bar(…) # including inserts
baz(…) # and updates
$dbh->commit; # commit the changes if we get this far
};
if ($@) {
warn “Transaction aborted because $@”;
# now rollback to undo the incomplete changes
# but do it in an eval{} as it may also fail
$dbh->rollback;
}
Hey! I just wanted to ask if you ever have any problems with hackers? My last blog (wordpress) was hacked and I ended up losing a few months of hard work due to no back up. Do you have any methods to protect against hackers?