MST
星途 面试题库

面试题:SQLite与Perl集成下复杂数据操作及事务处理

在SQLite中有`orders`表,字段有`order_id`(主键,整数)、`customer_id`(整数)、`order_date`(文本,格式'YYYY - MM - DD')、`total_amount`(数值)。还有`order_items`表,字段有`item_id`(主键,整数)、`order_id`(外键关联`orders`表的`order_id`)、`product_name`(文本)、`quantity`(整数)、`price`(数值)。现在要求用Perl结合SQLite语言扩展,完成以下操作:1. 开启一个事务;2. 插入一条新订单记录到`orders`表;3. 插入多条订单商品记录到`order_items`表,关联到新插入的订单;4. 若上述操作过程中有任何错误,回滚事务,若都成功则提交事务。请写出完整代码。
12.7万 热度难度
数据库SQLite

知识考点

AI 面试

面试题答案

一键面试
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;