在下载和安装Erlang后,在磁盘上的数千个文件之中,已经内置了一个相当完备的数据库管理系统,它的名字叫做Mnesia。它非常快,而且,更妙的是可以直接存储任意的Erlang数据结构
Mnesia可以根据需要灵活配置。比如说,既可以把数据表存储在内存中(数据的访问速度),也可以存储在磁盘上(数据的持久性),甚至还可以在不同的机器上建立同一份数据的多个副
test mnesia.erl
-modu1e(test_mnesia).
-import(lists, [foreach/2]).
-compile(export_all).
-include_lib("stdlib/include/qlc.hrl").
-record(shop, {item, quantity, cost}).
-record(cost, {name, price}).
-record(design, {id, plan}).
do_this_once() ->
mnesia:create_schema([node()]),
mnesia:start(),
mnesia:create_table(shop, [{attributes, record_info(fields, shop)}]),
mnesia:create_table(cost, [{attributes, record_info(fields, cost)}]),
mnesia:create_table(design, [{attributes, record_info(fields, design)}]),
mnesia:stop().
start() ->
mnesia:start(),
mnesia:wait_for_tables([shop, cost, design], 20000).
demo(select_shop) -> do(qlc:q([X || X <- mnesia:table(shop)]));
demo(select_some) -> do(qlc:q([{X#shop.item, X#shop.quantity} || X <- mnesia:table(shop)]));
demo(reorder) -> do(qlc:q([X#shop.item || X <- mnesia:table(shop), X#shop.quantity < 250]));
demo(join) -> do(qlc:q([X#shop.item || X <- mnesia:table(shop),
X#shop.quantity < 250,
Y <- mnesia:table(cost),
X#shop.item =:= Y#cost.name,
Y#cost.price < 2])).
do(Q) ->
F = fun() -> qlc:e(Q) end,
{atomic, Val} = mnesia:transaction(F),
Val.
example_tables() ->
[{shop, apple, 20, 2.3},
{shop, orange, 100, 3.8},
{shop, pear, 200, 3.6},
{shop, banana, 420, 4.5},
{shop, potato, 2456, 1.2},
{cost, apple, 1.5},
{cost, orange, 2.4},
{cost, pear, 2.2},
{cost, banana, 1.5},
{cost, potato, 0.6}].
add_shop_item(Name, Quantity, Cost) ->
Row = #shop{item = Name