我想将 csv 文件中的数据存储在 mnesia 数据库中(特别是在名为“ user ”的表中)
我在这个论坛中找到了这种解决方案:
创建名为csv.erl 的文件:
%%% --- csv parser in Erlang. ------
%%% To help process large csv files without loading them into
%%% memory. Similar to the xml parsing technique of SAX
-module(csv).
-compile(export_all).
parse(FilePath,ForEachLine,Opaque)->
case file:open(FilePath,[read]) of
{_,S} ->
start_parsing(S,ForEachLine,Opaque);
Error -> Error
end.
start_parsing(S,ForEachLine,Opaque)->
Line = io:get_line(S,''),
case Line of
eof -> {ok,Opaque};
"\n" -> start_parsing(S,ForEachLine,Opaque);
"\r\n" -> start_parsing(S,ForEachLine,Opaque);
_ ->
NewOpaque = ForEachLine(scanner(clean(clean(Line,10),13)),Opaque),
start_parsing(S,ForEachLine,NewOpaque)
end.
scan(InitString,Char,[Head|Buffer]) when Head == Char ->
{lists:reverse(InitString),Buffer};
scan(InitString,Char,[Head|Buffer]) when Head =/= Char ->
scan([Head|InitString],Char,Buffer);
scan(X,_,Buffer) when Buffer == [] -> {done,lists:reverse(X)}.
scanner(Text)-> lists:reverse(traverse_text(Text,[])).
traverse_text(Text,Buff)->
case scan("",$,,Text) of
{done,SomeText}-> [SomeText|Buff];
{Value,Rem}-> traverse_text(Rem,[Value|Buff])
end.
clean(Text,Char)->
string:strip(string:strip(Text,right,Char),left,Char).
创建功能测试:
test()->
ForEachLine = fun(Line,Buffer)-> io:format("Line: ~p~n",[Line]),Buffer end,
InitialBuffer = [],
csv:parse("/home/include/user.csv",ForEachLine,InitialBuffer).
但是此解决方案仅在 Erlang 控制台中显示数据(它显示 csv 文件中的每一行),但我的目标是将 csv 文件中的这些行存储在用户表中。
我已经创建了用户记录
-record(user, {id, firstname, lastname, birthday}).
将行从 csv 文件注册到用户表,我尝试使用
test()->
ForEachLine = fun(Line,Buffer)-> io:format("Line: ~p~n",[Line]),Buffer end,
InitialBuffer = [],
csv:parse("/home/test/user.csv",ForEachLine,InitialBuffer),
F = fun() ->
Line=#user{},
mnesia:write(Line),
{ok}
end,
{atomic, Val} = mnesia:transaction(F),
Val.
但是这个函数不会在用户表中插入数据