Erlang学习:MochiWeb + EMySQL

1. 下载MochiWeb

git clone git://github.com/mochi/mochiweb.git
2. 创建工程

$ cd mochiweb
$ make app PROJECT=mysql_web
3. 修改依赖

$ cd ../mysql_web
修改rebar.config,添加emysql

%% -*- erlang -*-
{erl_opts, [debug_info]}.
{deps, [
  {emysql, ".*",
   {git, "https://github.com/Eonblast/Emysql.git", {branch, "master"}}},
  {mochiweb, ".*",
   {git, "git://github.com/mochi/mochiweb.git", {branch, "master"}}}]}.
{cover_enabled, true}.
{eunit_opts, [verbose, {report,{eunit_surefire,[{dir,"."}]}}]}.


4.  下载依赖

$ ./rebar get_deps
5. 编译

$ ./rebar compile
修改代码:

mysql_web.erl

start() ->
    mysql_web_deps:ensure(),
    ensure_started(crypto),
    application:start(emysql),
    emysql:add_pool(hello_pool, 1, "root", "", "localhost", 3306, "my_database", utf8),
    application:start(mysql_web).

mysql_web_app.erl

loop(Req, DocRoot) ->
    "/" ++ Path = Req:get(path),
    try
        case Req:get(method) of
            Method when Method =:= 'GET'; Method =:= 'HEAD' ->
                case Path of
                    _ ->
                        %Req:serve_file(Path, DocRoot)
    					emysql:execute(hello_pool, <<"INSERT INTO expenses SET name = 'A', date = '2013-09-01', cost = 30, type_id = 2">>),
    					Result = emysql:execute(hello_pool, <<"select * from expenses">>),
						JSON = emysql_util:as_json(Result),
 						Req:respond({200, [{"Content-Type", "application/json"}], mochijson2:encode(JSON)})
                end;
            'POST' ->
                case Path of
                    _ ->
                        Req:not_found()
                end;
            _ ->
                Req:respond({501, [], []})
        end
    catch
        Type:What ->
            Report = ["web request failed",
                      {path, Path},
                      {type, Type}, {what, What},
                      {trace, erlang:get_stacktrace()}],
            error_logger:error_report(Report),
            %% NOTE: mustache templates need \ because they are not awesome.
            Req:respond({500, [{"Content-Type", "text/plain"}],
                         "request failed, sorry\n"})
    end.

数据库my_database,新建expenses表:

DROP TABLE IF EXISTS `expenses`;
CREATE TABLE `expenses` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(128) DEFAULT NULL,
  `date` date DEFAULT NULL,
  `cost` float DEFAULT NULL,
  `type_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `type_id` (`type_id`),
  CONSTRAINT `expenses_ibfk_1` FOREIGN KEY (`type_id`) REFERENCES `types` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值