使用Erlang Mysql驱动程序

时间:2016-05-16 11:40:05

标签: mysql erlang

我想让erlang-mysql-driver正常工作,我设法设置并进行查询,但有两件事我不能做。(https://code.google.com/archive/p/erlang-mysql-driver/issues

(顺便说一句,我是Erlang的新手)

以下是连接MySQL的代码。

<erl>
out(Arg) -> 
            mysql:start_link(p1, "127.0.0.1", "root", "azzkikr", "MyDB"),
            {data, Result} = mysql:fetch(p1, "SELECT * FROM messages").
</erl>

1。我无法从表中获取数据。

mysql.erl不包含有关如何获取表数据的任何具体信息,但这是我能走得最远的。

        {A,B} = mysql:get_result_rows(Result),
        B.

结果就是这样:

ERROR erlang code threw an uncaught exception:
 File: /Users/{username}/Sites/Yaws/index.yaws:1
Class: error
Exception: {badmatch,[[4,0,<<"This is done baby!">>,19238],
                      [5,0,<<"Success">>,19238],
                      [6,0,<<"Hello">>,19238]]}
Req: {http_request,'GET',{abs_path,"/"},{1,1}}
Stack: [{m181,out,1,
              [{file,"/Users/{username}/.yaws/yaws/default/m181.erl"},
               {line,18}]},
        {yaws_server,deliver_dyn_part,8,
                     [{file,"yaws_server.erl"},{line,2818}]},
        {yaws_server,aloop,4,[{file,"yaws_server.erl"},{line,1232}]},
        {yaws_server,acceptor0,2,[{file,"yaws_server.erl"},{line,1068}]},
        {proc_lib,init_p_do_apply,3,[{file,"proc_lib.erl"},{line,240}]}]

据我所知,我需要获取第二个元素并使用 foreach 来获取每个数据,但字符串以不同的格式返回,如查询字符串为Success但返回的字符串为{{1 }}

<<"Success">>

第一个问题是:如何从表中获取数据?

2。如何使用变量将值插入表中?

我可以使用这种方法将数据插入表中:

{badmatch,[[4,0,<<"This is done baby!">>,19238],
                      [5,0,<<"Success">>,19238],
                      [6,0,<<"Hello">>,19238]]}

但是有两件事我遇到了麻烦, 1.我在没有 Msg = "Hello World", mysql:prepare(add_message,<<"INSERT INTO messages (`message`) VALUES (?)">>), mysql:execute(p1, add_message, [Msg]). <<运算符的情况下插入数据,因为当我执行>>时,erlang会抛出异常(我认为我做错了),我不知道它们是必需的但没有它们我能够将数据插入表格,除了这个错误让我在执行后困扰我:

Msg = << ++ "Hello World" >>,
当我命令插入数据时,

返回的原子是yaws code at /Users/{username}/Yaws/index.yaws:1 crashed or ret bad val:{updated, {mysql_result, [], [], 1, []}} Req: {http_request,'GET',{abs_path,"/"},{1,1}} 问题2是:如何以正确的方式将数据插入表中?

1 个答案:

答案 0 :(得分:1)

错误:

{badmatch,[[4,0,<<"This is done baby!">>,19238],
                      [5,0,<<"Success">>,19238],
                      [6,0,<<"Hello">>,19238]]}

告诉您返回的值为:

[[4,0,<<"This is done baby!">>,19238],
 [5,0,<<"Success">>,19238],
 [6,0,<<"Hello">>,19238]]

显然无法与{data, Data}{A, B}匹配。您可以按以下方式获取数据:

<erl>
out(Arg) -> 
    mysql:start_link(p1, "127.0.0.1", "root", "azzkikr", "MyDB"),
    {ehtml,
     [{table, [{border, "1"}],
       [{tr, [],
         [{td, [],
           case Val of
               _ when is_binary(Val) -> yaws_api:htmlize(Val);
               _ when is_integer(val) -> integer_to_binary(Val)
           end}
          || Val <- Row
         ]}
        || Row <- mysql:fetch(p1, "SELECT * FROM messages")
       ]}
     ]
    }.
</erl>