Ont*_*nty 4 database erlang transactions mnesia
我的代码有点问题.我有一个包含汽车详细信息,名称,价格和数量的表格,因此我正在尝试创建一个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).
Run Code Online (Sandbox Code Playgroud)
请帮助我如何编写从商店购买汽车的功能.
但是你的实现工作正常,除了你在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).
Run Code Online (Sandbox Code Playgroud)