2012-03-04 110 views
3

我的代码有点问题。我有一个包含汽车详细信息,名称,价格和数量的表格,所以我试图创建一个名为buy的功能,该功能将用于购买特定的汽车。当用户购买例如5辆宝马汽车时,他们将拨打buy_car(bmw,5)。在此之后,我想更新宝马汽车的新数量。如何更新Erlang中的Mnesia表

我的尝试是在下面,但我似乎无法解决它,我是新来的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). 

请帮助我如何写一个从商店购买汽车的功能。

回答

5

但是你的实现工作正常,除非你在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). 
+0

非常感谢你,这正是我所需要的,我对erlang很陌生,但对其他语言非常好,谢谢你的帮助。 5 * – Onty 2012-03-05 00:29:15

-1

我会做类似如下:

 
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复制到磁盘上,以便进行每次更新(由于性能问题),而是以时间触发的方式进行更新。

+0

谢谢你的回应,你知道我可以从已经在表格中的数量中减去NCars,然后用新的数量值更新记录吗?例如数量=数量 - NCars,是否可以,如果我这样写? – Onty 2012-03-04 14:38:22

相关问题