我的代码有点问题。我有一个包含汽车详细信息,名称,价格和数量的表格,因此我尝试创建一个名为buy
的功能,用于购买特定的汽车。当用户购买5辆宝马汽车时,他们会拨打buy_car(bmw,5)
。在此之后,我想更新宝马汽车的新数量值。
我的尝试在下面,但我似乎无法解决它,我是Erlang的新手。
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).
请帮助我如何编写从商店购买汽车的功能。
答案 0 :(得分:6)
但是你的实现工作正常,除了你在mnesia:write(Leftcars)之后添加非法逗号。 这是有效的代码(我尝试将你的实现作为buy_car2)。
-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).
答案 1 :(得分:0)
我会做类似下面的事情:
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).
要使用上述方法,必须将mnesia表创建为“ram_copies”且没有复制节点。此外,如果发生了大量更新,您可能不希望因性能问题而将ram_copies复制到磁盘以进行每次更新,而是以时间触发的方式执行此操作。