我正在使用Erlang的mysql-otp驱动程序。它似乎工作正常,但没有关于使用它将多行插入表中的文档。
单行插入的简单用例:
ok = mysql:query(Pid, "INSERT INTO mytable (id, bar) VALUES (?, ?)", [1, 42]).
但我需要插入多个值,我可以这样做吗?
ok = mysql:query(Pid, "INSERT INTO mytable (id, bar) VALUES (?, ?)", [(1, 42),(2, 36), (3,12)]).
文档说明Params = [term()],所以可能不是,这是一个无赖。
答案 0 :(得分:1)
您可以在参数上组合使用lists:foldl/3和lists:join/2来创建所需的查询格式:
L = [[1, 42],[2, 36], [3,12]],
PreparedList = lists:foldl(fun (Params, Inserts) -> Inserts ++ [io_lib:format("(~p,~p)", Params)] end, [], L),
%% Then you need to join these with a comma:
Prepared = lists:flatten(lists:join(",", PreparedList)),
%% this will result in "(1,42),(2,36),(3,12)"
现在你只需要用这个Prepared
变量调用mysql插件:
ok = mysql:query(Pid, "INSERT INTO mytable (id, bar) VALUES ?", [Prepared]).
%% The query will look like: "INSERT INTO mytable (id, bar) VALUES (1,42),(2,36),(3,12)"
答案 1 :(得分:0)
我不认为这个驱动程序或mysql可以做这样的事情。
我认为你应该这样做,如下面
insert_mytable(Data)->
{ok,Ref} = mysql:prepare(Pid,insert_mytable,"INSERT INTO mytable (id, bar) VALUES (?, ?)"),
loop_insert(_Pid,Ref,Data).
loop_insert(_Pid,_Ref,[])-> ok;
loop_insert(Pid,Ref,[H|T])->
ok = mysql:execute(Pid,Ref,H),
loop_insert(Pid,Ref,T).