[Erlang novice grow diary] Mnesia database CRUD operations

Initialization:

1, when the (optional) starts the Erlang, provided the location of the root directory:

  erl -mnesia you you

Use your schema to store directory instead Dir.

Example:

erl -mnesia dir '"db"'

 

2, the establishment of schema:

  mnesia:create_schema(DiscNodes) -> ok | {error, Reason}

The official document: http://www.erlang.org/doc/man/mnesia.html#create_schema-1

More details about the schema, refer to "Erlang Programming" on page 295 Configuring Mnesia

Note: When creating a database, build schema operations, need only be done once.

 

3. Start the database

  mnesia:start() -> ok | {error, Reason}

 

Create a table:

1, Statement record

  Mnesia database table that contains the Erlang record. Typically, record type name is the table name.

Example:

-record(users, {username, password}).

Statement record, to create a table "users", stores the user name "" and the password "password".

 

2, create a table

  mnesia:create_table(Name, TabDef) -> {atomic, ok} | {aborted, Reason}

This function creates a table called Name according to TabDef. Name of record type, TabDef a list of tuples, the format is {Key, Value}.

For more details, refer to the official document: http://www.erlang.org/doc/man/mnesia.html#create_table-2

Example:

mnesia:create_table(users, [{attributes, record_info(fields, users)}]).

 

C:

Use the transaction, add a data item in the data table:

c(Id, Username, Password) ->
    User = #users{id = Id, username = Username, password = Password},
    Fun = fun() ->
        mnesia:write(User)
    end,
    mnesia:transaction(Fun).

 

R:

 Using transactions, query data table:

r(Id) ->
    Fun = fun() ->
        qlc:e(qlc:q([User || User <- mnesia:table(users), User#users.id =:= Id]))
    end,
    mnesia:transaction(Fun).

Note: Use qlc module queries, you need to file the top of the statement "-include_lib (" stdlib / include / qlc.hrl "), or will cause" Warning: qlc: q / 1 called, but "at compile time." Qlc.hrl " not included "warning.

 

In:

The first recording of the primary key attribute.

The default data type table is "set". In one set (set), all the records with a unique key, in a package (Bag), the data may have several same key, but the content is recorded only.

If a non-unique data is stored in the original table, the records will be simple conflict coverage.

 

D:

Using transactions, delete data items:

d(Id) ->
    Fun = fun() ->
        mnesia:delete({users, Id})
    end,
    mnesia:transaction(Fun).

 

Dirty operations:

1, about 10 times faster than the speed of operation of the transaction;

2, occasional dirty read to avoid dirty write.

 

Visualization tools:

  Erlang comes with a Mnesia and ETS can see table viewer, use tv: start () start.

Reproduced in: https: //www.cnblogs.com/dyingbleed/archive/2012/09/05/2668959.html

Guess you like

Origin blog.csdn.net/weixin_34336292/article/details/93447133