Database 如何在Erlang中更新Mnesia表

Database 如何在Erlang中更新Mnesia表,database,transactions,erlang,mnesia,Database,Transactions,Erlang,Mnesia,我的代码有点问题。我有一个包含汽车详细信息、名称、价格和数量的表,因此我试图创建一个名为buy的函数,用于购买特定的汽车。当用户购买例如5辆BMW汽车时,他们会调用buy\u car(BMW,5)。现在,在这之后,我想更新宝马汽车数量的新值 我的尝试如下,但我似乎无法解决它,我是新来的二郎 buy_car(X,Ncars) -> F = fun() -> %% ----first i find the number of car X available i

我的代码有点问题。我有一个包含汽车详细信息、名称、价格和数量的表,因此我试图创建一个名为
buy
的函数,用于购买特定的汽车。当用户购买例如5辆BMW汽车时,他们会调用
buy\u car(BMW,5)
。现在,在这之后,我想更新宝马汽车数量的新值

我的尝试如下,但我似乎无法解决它,我是新来的二郎

buy_car(X,Ncars) ->

    F = fun() ->

        %% ----first i find the number of car X available in the shop
        [Xcars] = mnesia:read({car,X}),
        Nc = Xcars#car.quantity,
        Leftcars = Xcars#car{quantity = Nc - Ncars},

        %% ---now we update the database
        mnesia:write(Leftcars),

    end,
    mnesia:transaction(F).

请帮助我如何编写从商店购买汽车的函数。

我将执行以下操作:

考虑到记录的定义如下: -记录(car_记录,{car,quantity})。 以下功能将更新数据: 购买汽车(X,NCAR)-> 行=#car_记录{car=X,数量=NCars}。 mnesia:ets(fun()->mnesia:dirty_write(Row)end), mnesia:更改表格复制类型(引导数据、节点()、光盘复制)。

要使用上述方法,必须将mnesia表创建为“ram_拷贝”,并且没有复制节点。另外,如果有很多更新发生,由于性能问题,您可能不希望每次更新都将ram_拷贝复制到磁盘,而是以时间触发的方式进行。

但是,除了在mnesia:write(Leftcars)之后添加非法逗号外,您的实现工作正常。 下面是有效的代码(我尝试了您作为buy_car2的实现)


感谢您的回复,您知道如何从表中已有的数量中减去NCAR,然后使用新的数量值更新记录吗?例如quantity=quantity-NCars,如果我这样写可以吗?非常感谢,这正是我所需要的,我是erlang的新手,但对其他语言非常精通,谢谢你的帮助。5* Considering the record is defined as : -record(car_record, {car, quantity}). The following function will update the data: buy_car(X,NCars) -> Row = #car_record{car = X, quantity = NCars}. mnesia:ets(fun()-> mnesia:dirty_write(Row) end), mnesia:change_table_copy_type(guiding_data, node(), disc_copies).
-module(q).

-export([setup/0, buy_car/2, buy_car2/2]).

-record(car, {brand, quantity}).

setup() ->
    mnesia:start(),
    mnesia:create_table(car, [{attributes, record_info(fields, car)}]),
    mnesia:transaction(fun() -> mnesia:write(#car{brand=bmw, quantity=1000}) end).

buy_car(Brand, Ncars) ->
    F = fun() ->
         [Car] = mnesia:read(car, Brand), % crash if the car is missing
         mnesia:write(Car#car{quantity = Car#car.quantity - Ncars})
    end,
    mnesia:transaction(F).

buy_car2(X,Ncars) ->
    F = fun() ->
        %% ----first i find the number of car X available in the shop
        [Xcars] = mnesia:read({car,X}),
        Nc = Xcars#car.quantity,
        Leftcars = Xcars#car{quantity = Nc - Ncars},
        %% ---now we update the database
        mnesia:write(Leftcars)
    end,
    mnesia:transaction(F).