【昆山人在上海】

生在昆山_人在上海:漂泊在美国,纽约好冷啊!!!

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;







            
阅读更多
个人分类: Erlang实践
想对作者说点什么? 我来说一句

HebernateMysql

2014年04月15日 6.43MB 下载

erlang mysql

2014年02月22日 19KB 下载

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭