ErlyWeb的MySQL数据库连接以及操作

      首先从http://erlyweb.org中下载最新的ErlyWeb,解压缩到D盘.然后从控制台进入到erlyweb所在的目录后,执行make.bat批处理文件,把scr目录的源码编译后复制到ebin目录中,其中src源代码中包含了my-sql的驱动

     把编译后的erlyweb复制到erlang安装目录下的lib文件夹内.进入控制台,启动erlang shell 环境,利用ErlyWeb的erldb模块来连接mysql.

3> erlydb:start(mysql,[{hostname,"localhost"},{username, "root"},{password, "123
456"},{database, "test"},{pool_size, 10}]).
mysql_conn:620: greeting version "5.0.22-community-nt" (protocol 10) salt "{Y)\\
xes2" caps 41516 serverchar <<28,2,0,

                              0,0,0,0,

                              0,0,0,0,

                              0,0,0,0,

                              0>>salt2 ">\"+O1FL+2XF7"
mysql_auth:187: mysql_auth send packet 1: <<5,162,0,0,64,66,15,0,8,0,0,0,0,0,0,
                                            0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
                                            114,111,111,116,0,20,30,255,40,235,
                                            185,0,22,251,145,205,181,140,134,
                                            215,13,26,100,70,196,49>>
mysql_conn:426: fetch <<"use test">> (id <0.50.0>)
ok

 

不知道是mysql驱动的原因还是我本机的问题,有的时候连接是会提示如下的错误:

2> erlydb:start(mysql,[{hostname,"127.0.0.1"},{username, "root"},{password, "123
456"},{database, "test"},{pool_size, 10}]).
mysql_conn:354: failed connecting to "127.0.0.1":3306 : {error,"timeout"}
mysql:502: failed starting first MySQL connection handler, exiting
ok

 

需要多次连接才能成功.连接成功后,就可以操作数据库了,比如查询一个表的数据:

9> mysql:fetch(erlydb_mysql,<<"select * from userinfo">>).
mysql_conn:426: fetch <<"select * from userinfo">> (id <0.50.0>)
{data,{mysql_result,[{<<"userinfo">>,<<"userId">>,10,'LONG'},
                     {<<"userinfo">>,<<"username">>,45,'VAR_STRING'},
                     {<<"userinfo">>,<<"passWord">>,45,'VAR_STRING'},
                     {<<"userinfo">>,<<"email">>,2,'VAR_STRING'},
                     {<<"userinfo">>,<<"addressid">>,10,'LONG'},
                     {<<"userinfo">>,<<"userPassWord">>,6,'VAR_STRING'}],
                    [[1,<<"test">>,<<"123456">>,<<>>,1,undefined]],
                    0,[]}}

其中erlydb_mysql是一个原子, 前面我们连接数据库的时候设置了连接池默认为10, erlydb_mysql是连接池中的默认的id,如果不清楚这个的话,可以通过erlydb_mysql:get_default_pool_id().这个语句来获取。当然不用erldb来连接mysql也是可以的,我们可以直接用mysql:start_link(p1, [{hostname,"localhost"},{username, "root"},{password, "123456"},{database, "test"}])来进行数据库连接,其中p1就是statement。

你可能感兴趣的:(sql,mysql,erlang)