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,"."}]}}]}.
$ ./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;