Express示例(02):图书管理系统-数据库(MariaDB)

准备

模块

  • express
  • art-template
  • body-parser
  • express-art-template
  • mysql

安装命令

npm install express art-template body-parser express-art-template mysql --save

系统

功能

  • 主页面
  • 增加
  • 修改
  • 删除
  • 数据库(MariaDB)

目录结构

mybook
 |-node_modules
 |-views
    |-index.art
    |-addBook.art
    |-editBook.art
 |-public
    |-style.css
 |-index.js
 |-router.js
 |-service.js
 |-db.js
 |-package.json

实现

  1. 创建index.js
  2. 创建package.json
npm init -y
  1. 安装第三方
npm install express art-template express-art-template body-parser mysql --save
  1. index.js
/*
    图书管理系统-入口文件
 */

const express = require('express');
const template = require('art-template');
const bodyParser = require('body-parser');
const path = require("path");
const router = require('./router.js');
const app = express();


//启动静态资源服务
app.use('/www',express.static('public'));

//设置模板引擎
//设置模板的路径
app.set('views',path.join(__dirname,'views'));
//设置模板引擎
app.set('view engine','art');
//使用express兼容art-template模板引擎
app.engine('art',require('express-art-template'));


//处理请求参数
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());

//启动服务器
//配置路由
app.use(router);
//监听端口
app.listen(3000,()=>{
    console.log("服务启动……");
});

  1. 创建目录
    ./views
    ./public

  2. db.js

/*
    封装通用数据库通用api
 */

const mysql = require('mysql');

/**
 *
 * @param sql
 * @param data
 * @param callback
 */
exports.base = (sql, data, callback) => {
    /*
        操作数据库基本步骤
     */
    //创建数据库连接
    const connection = mysql.createConnection({
        host: 'localhost',  //数据库所在的服务器的域名或者IP地址
        user: 'root',//用户名
        password: 'admin',//密码
        database: 'book', //数据库
        port: '4406'  //端口号
    });

//执行连接操作
    connection.connect();

//操作数据库
    connection.query(sql, data, function (error, results, fields) {
        if (error) throw error;
        callback(results);
    });


//关闭数据库
    connection.end();
}
  1. 路由:./router.js
/*
    路由模块
 */

const express = require('express');
const router = express.Router();
const service = require('./service');

//渲染登录
router.get('/',service.showIndex);

//打开新增页面
router.get('/toAddBook',service.toAddBook);

//新增图书
router.post('/addBook',service.addBook);

//打开编辑页面
router.get('/toEditBook',service.toEditBook);

//提交编辑
router.post('/editBook',service.editBook);

//删除图书
router.get('/deleteBook',service.deleteBook);

module.exports = router;
  1. 业务处理:./service.js
/*
    业务模块
 */

const data = require('./data.json');
const path = require('path');
const fs = require('fs');
const db = require('./db');
//自动生成图书编号
let maxBookCode = () => {
    let arr = [];
    data.forEach((item) => {
        arr.push(item.id);
    });
    return Math.max.apply(null, arr);
}

//渲染主页面
exports.showIndex = (req, res) => {
    //
    let sql = 'select * from book';
    let data = null;
    db.base(sql, null, (result) => {
        res.render('index', {list: result});
    });
}

//添加图书
//跳转到添加图书页面
exports.toAddBook = (req, res) => {
    res.render('addBook', {});
}

//添加图书保存数据
exports.addBook = (req, res) => {
    //获取表单数据
    let info = req.body;
    let book = {};
    for (let key in info) {
        book[key] = info[key];
    }

    //插入数据库
    let sql = 'insert into book set ? ';
    db.base(sql, book, (result) => {
        if (result.affectedRows == 1) {
            res.redirect('/');
        }
    });
}

//跳转编辑页面
exports.toEditBook = (req, res) => {
    let id = req.query.id;
    let book = null;
    let sql = 'select * from book where id = ?';
    let data = [id];
    db.base(sql, data, (result) => {
        res.render('editBook', result[0]);
    });
}

//编辑图书,更新数据
exports.editBook = (req, res) => {
    let info = req.body;
    let sql = 'update book set name=?,author=?,category=?,description=? where id = ?';
    let data = [info.name, info.author, info.category, info.description, info.id];
    db.base(sql, data, (result) => {
        if (result.affectedRows == 1) {
            res.redirect('/');
        }
    });
}

//删除
exports.deleteBook = (req, res) => {
    let id = req.query.id;
    let sql = 'delete from book where id = ?';
    let data = [id];
    db.base(sql, data, (result) => {
        if (result.affectedRows == 1) {
            res.redirect('/');
        }
    });
}
  1. ./views/index.art
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>图书管理系统</title>
    <link rel="stylesheet" type="text/css" href="/www/style.css"></link>
</head>
<body>
<div class="title">
    图书管理系统<a href="/toAddBook">新增图书</a>
</div>
<div class="content">
    <table cellspacing="0" cellpadding="0">
        <thead>
        <tr>
            <th>编号</th>
            <th>名称</th>
            <th>作者</th>
            <th>分类</th>
            <th>描述</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
            {{each list}}
            <tr>
                <td>{{$value.id}}</td>
                <td>{{$value.name}}</td>
                <td>{{$value.author}}</td>
                <td>{{$value.category}}</td>
                <td>{{$value.description}}</td>
                <td><a href="/toEditBook?id={{$value.id}}">修改</a>|<a href="deleteBook?id={{$value.id}}">删除</a></td>
            </tr>
            {{/each list}}
        </tbody>
    </table>
</div>
</body>
</html>
  1. ./public/style.css
.title{
    text-align: center;
    background-color: #abef98;
    height: 50px;
    line-height: 50px;
    font-size: 24px;
}
.content{
    background-color: lightblue;
}
.content table{
    width: 100%;
    text-align: center;
    border-right: 1px solid orange;
    border-bottom: 1px solid orange;
}
.content td,th{
    border-left: 1px solid orange;
    border-top: 1px solid orange;
    height: 40px;
    line-height: 40px;
}
  1. ./views/addBook.art
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>新增图书</title>
</head>
<body>
<form action="/addBook" method="post">
    名称:<input type="text" name="name"><br>
    作者:<input type="text" name="author"><br>
    分类:<input type="text" name="category"><br>
    描述:<input type="text" name="description"><br>
    <input type="submit">
</form>
</body>
</html>
  1. ./views/editBook.art
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>编辑图书</title>
</head>
<body>
<div>修改图书</div>
<form action="/editBook" method="post">
    <input type="hidden" name="id" value="{{id}}">
    名称:<input type="text" name="name" value="{{name}}"><br>
    作者:<input type="text" name="author" value="{{author}}"><br>
    分类:<input type="text" name="category" value="{{category}}"><br>
    描述:<input type="text" name="description" value="{{description}}"><br>
    <input type="submit">
</form>
</body>
</html>
  1. 数据库结构
1、数据库:book
2、表:book
/*
 Navicat Premium Data Transfer

 Source Server         : mybook
 Source Server Type    : MariaDB
 Source Server Version : 100506
 Source Host           : localhost:4406
 Source Schema         : book

 Target Server Type    : MariaDB
 Target Server Version : 100506
 File Encoding         : 65001

 Date: 26/10/2020 14:50:48
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for book
-- ----------------------------
DROP TABLE IF EXISTS `book`;
CREATE TABLE `book`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
  `author` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
  `category` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
  `description` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 10 CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of book
-- ----------------------------
INSERT INTO `book` VALUES (2, '西游记', '吴承恩', '文学', '猴子');
INSERT INTO `book` VALUES (3, '三国演义', '罗贯中', '文学', '三国');
INSERT INTO `book` VALUES (4, '水浒传', '施耐庵', '文学', '宋朝');
INSERT INTO `book` VALUES (5, '红楼梦', '曹雪芹', '文学', '清朝');
INSERT INTO `book` VALUES (8, '笑傲江湖', '金庸', '文学', '宋朝');

SET FOREIGN_KEY_CHECKS = 1;

上一篇:tensorflow源码阅读(c++)(一)


下一篇:3、Node.js使用模板引擎简单介绍