This repository has been archived on 2021-11-25. You can view files and clone it, but cannot push or open issues or pull requests.
DBHomework/addbook.cpp
kiritow d4ee2b3edb Update DBHomework.
And I'm gonna to sleep now.
2017-11-19 23:28:30 +08:00

168 lines
6.1 KiB
C++

#include "Session.h"
#include "Util.h"
#include "json.hpp"
using namespace std;
using json = nlohmann::json;
#define postval(NAME) string NAME=req.post[#NAME]
int main()
{
Request req;
Session se(req);
Response res;
json j;
auto jsonfail=[&](int errcode,const std::string& errmsg)
{
j["success"]=0;
j["errcode"]=errcode;
j["errmsg"]=errmsg;
};
if(se.isNew()||se.getUser().empty())
{
jsonfail(1,"Please Login First");
}
if(req.requestMethod=="POST")
{
if(req.post["isbn"].empty() ||
req.post["bookname"].empty() ||
req.post["booktype"].empty() ||
req.post["author"].empty() ||
req.post["publisher"].empty() ||
req.post["pubdate"].empty() ||
req.post["status"].empty() )
{
jsonfail(3,"Missing parameter");
}
else
{
postval(isbn);
postval(bookname);
postval(booktype);
postval(author);
postval(publisher);
postval(pubdate);
postval(status);
DBInfo db;
if(db.readConfig()<0)
{
jsonfail(5,"Failed to read config");
}
else
{
MySQLConn conn;
if(db.connectProxy(conn)<0)
{
jsonfail(6,"Failed to connect DB");
}
else
{
int counter;
if(conn.exec("select count(class_id) from bs_book",[&](MySQLResult& res)
{
res.stepRow([&](char** val,unsigned long* len)
{
counter=ParseInt(val[0]);
});
})<0)
{
jsonfail(7,"Failed to execute SQL at Step 1");
}
else
{
if(counter==0)
{
/// First book, class_id = 1, goto step 3 directly.
if(conn.exec(make_str("insert into bs_book values (1,'",
isbn,
"','",
bookname,
"','",
booktype,
"','",
author,
"','",
publisher,
"','",
pubdate,
"',2)"),nullptr)<0)
{
jsonfail(9,"Failed to execute SQL at step 3");
}
else
{
if(conn.getAffectedRows()!=1)
{
jsonfail(10,"Failed to execute SQL at step 4");
}
else
{
j["success"]=1;
}
}
}
else
{
/// Try to find the max class id.
int maxId;
if(conn.exec("select max(class_id) from bs_book ",[&](MySQLResult& res)
{
res.stepRow([&](char** val,unsigned long* len)
{
maxId=ParseInt(val[0]);
});
})<0)
{
jsonfail(8,"Failed to execute SQL at step 2");
}
/// Give new book.class_id as maxId+1
if(conn.exec(make_str("insert into bs_book values (",
maxId+1,
",'",
isbn,
"','",
bookname,
"','",
booktype,
"','",
author,
"','",
publisher,
"','",
pubdate,
"',2)"),nullptr)<0)
{
jsonfail(9,"Failed to execute SQL at step 3");
}
else
{
if(conn.getAffectedRows()!=1)
{
jsonfail(10,"Failed to execute SQL at step 4");
}
else
{
j["success"]=1;
}
}
}
}
}
}
}
}
else
{
jsonfail(2,"Unsupported request method.");
}
res.content.append(j.dump());
res.show();
return 0;
}