use strict;
use warnings;
use DBI;
# 连接到SQLite数据库
my $dbh = DBI->connect('dbi:SQLite:dbname=test.db', '', '', {
RaiseError => 1,
AutoCommit => 0
}) or die $DBI::errstr;
eval {
# 开启事务
$dbh->begin_work;
# 插入一条新订单记录到orders表
my $order_id;
my $order_sth = $dbh->prepare("INSERT INTO orders (customer_id, order_date, total_amount) VALUES (?,?,?)");
$order_sth->execute(1, '2023 - 01 - 01', 100.00);
$order_id = $dbh->last_insert_id(undef, undef, 'orders', 'order_id');
# 插入多条订单商品记录到order_items表,关联到新插入的订单
my @items = (
['Product A', 2, 25.00],
['Product B', 1, 50.00]
);
my $item_sth = $dbh->prepare("INSERT INTO order_items (order_id, product_name, quantity, price) VALUES (?,?,?,?)");
foreach my $item (@items) {
$item_sth->execute($order_id, $item->[0], $item->[1], $item->[2]);
}
# 提交事务
$dbh->commit;
};
if ($@) {
# 若有错误,回滚事务
$dbh->rollback;
die "Transaction failed: $@";
}
$dbh->disconnect;