使用mysql otp driver for erlang插入多行mysql:query

zbsbpyhn  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(456)

我正在使用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()],所以可能不是,这是一个麻烦。

oknwwptz

oknwwptz1#

你当然可以把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)"

现在您只需要调用mysql insert Prepared 变量:

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)"
camsedfj

camsedfj2#

我不认为这个驱动程序或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).

相关问题