Mnesia数据库删除实现和事务处理
-module(test_mnesia).
-include_lib("stdlib/include/qlc.hrl").-record(shop, {item, quantity, cost}).
%% API
-export([insert/3, select/0, select/1, delete/1, transaction/1,start/0, do_this_once/0]).
start() ->mnesia:start().insert(Name, Quantity, Cost) ->Row = #shop{item = Name, quantity = Quantity, cost = Cost},io:format("insert ~p~n", [Row]),F = fun() ->mnesia:write(Row)end,mnesia:transaction(F).delete(Item) ->Oid = {shop, Item},io:format("delete ~p~n", [Oid]),F = fun() ->mnesia:delete(Oid)end,mnesia:transaction(F).select() ->do(qlc:q([X || X <- mnesia:table(shop)])).
select(Num) ->do(qlc:q([X || X <- mnesia:table(shop), X#shop.quantity =< Num])).
%%事务函数
transaction(Num) ->F = fun() ->[Apple] = mnesia:read({shop, apple}),NApple = Apple#shop.quantity,Apple1 = Apple#shop{quantity = NApple + Num},mnesia:write(Apple1),[Orange] = mnesia:read({shop, orange}),NOrange = Orange#shop.quantity,ifNOrange >= Num ->N1 = NOrange - Num,Orange1 = Orange#shop{quantity = N1},mnesia:write(Orange1);true ->mnesia:abort(oranges)endend,mnesia:transaction(F).
do(Q) ->F = fun() ->qlc:e(Q)end,{atomic, Val} = mnesia:transaction(F),Val.do_this_once() ->mnesia:create_schema([node()]),mnesia:start(),mnesia:create_table(shop, [{attributes, record_info(fields, shop)}]),mnesia:stop().
删除功能实现
开始有pear后删除就没有pear了
事务功能实现
事务是一个整体,里面方法对数据库的操作要么同时操作完毕,要么都不操作
我的事务函数中输入数据,将苹果增加改数量,橘子减少该数量
开始操作成功,数据正确
后面橘子数量不足,因此苹果的改动也没有完成,数据正确