cnpm install -g express-generator
express peifang-server
cd peifang-server
cnpm install
npm start
const sqlconfig = {
host: 'localhost', // 连接地址
user: 'root', //用户名
password: 'root', //密码
port: 3306 , //端口号
database: 'peifang' //数据库名
}
module.exports = sqlconfig
const mysql = require('mysql')
const sqlconfig = require('../config/index.js')
const e = require("express");
/**
* 连接数据库的两种简单方式:
* 1. 使用mysql.createConnection连接数据库。
* 2. 使用连接池 pool.createPool()。
*/
// 方式1 使用mysql.createConnection连接数据库
let mySql = (sql, data) => {
return new Promise((resolve, reject) => {
//连接数据库
let conn = mysql.createConnection(sqlconfig)
conn.query(sql, data, (err, result) => {
console.log(err, result, '执行SQL语句');
// 错误信息
if (err) {
// 当连接不再使用时,用conn对象的release方法将其归还到连接池中
conn.release()
reject(err);
} else {
resolve(result)
}
})
})
}
// 方式2 使用连接池 pool.createPool()
let pool = mysql.createPool(sqlconfig)
// 封装执行数据库
pool.getConnection((err, conn) => {
return new Promise((resolve, reject) => {
if (err) {
// 当连接不再使用时,用conn对象的release方法将其归还到连接池中
conn.release()
reject(err)
} else {
resolve(conn)
}
})
})
// 方式3 使用mysql.createConnection连接数据库并进行基础封装
const conn = mysql.createConnection(sqlconfig)
conn.connect(err => {
if (err) {
console.log("连接失败")
} else {
console.log("连接成功,当前连接线程ID"+conn.threadId);
}
})
module.exports = {
mySql,
pool,
conn,
}
ALTER TABLE peifang.history MODIFY COLUMN `create_time` datetime NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间';
ALTER TABLE peifang.scheme MODIFY COLUMN `createTime` datetime NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间';
ALTER TABLE peifang.part MODIFY COLUMN `create_time` datetime NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间';
var partRouter = require('./routes/part');
var schemeRouter = require('./routes/scheme');
var schemeDetailRouter = require('./routes/scheme_detail');
var historyRouter = require('./routes/history');
app.use('/part', partRouter);
app.use('/scheme', schemeRouter);
app.use('/schemeDetail', schemeDetailRouter);
app.use('/history', historyRouter);
router.get("/list", (req, res) => {
const sql = "SELECT * FROM part";
conn.query(sql,function(err,result){
if(err){
res.send({
status: 400,
msg: '查询语句执行异常'
})
}
res.json({
status: 200,
msg: '查询成功',
list: result
})
})
});
router.get("/listByPage", (req, res) => {
const size = Number(req.query.size)
const page = Number(req.query.page)
const start = (page - 1) * size;
// 从第start开始取,一共取size个数据
const sql = `SELECT * FROM part LIMIT ${start}, ${size}`;
const countSql = 'SELECT count(id) as total FROM part'
conn.query(sql, (err, data) => {
if(err){
res.send({
status: 400,
msg: '查询语句执行异常'
})
}
conn.query(countSql, (error, count) => {
if(err){
res.send({
status: 400,
msg: '查询语句执行异常'
})
}
console.log(count, 'count')
res.json({
status: 200,
msg: '查询成功',
list: data,
total: count[0].total
})
})
})
})
router.get("/partInfo/:id", (req, res) => {
const id = String(req.params.id)
const sql = `SELECT * FROM part WHERE id = '${id}'`
conn.query(sql, (error, data) => {
if (error) {
res.json({
status: 404,
msg: err.message
});
} else {
res.json({
status: 200,
msg: '查询成功',
list: data
})
}
})
})
router.post("/addPart", (req, res) => {
const { name , price, MJProportion, proteinProportion, calciumProportion, phosphorusProportion} = req.body
const querySql = `SELECT * FROM part WHERE name = '${name}'`
conn.query(querySql, (err, data) => {
console.log(err, data)
if (data.length > 0) {
res.send({
status: 400,
msg: '当前成分已存在!'
})
} else {
// 构建sql语句
const sql = 'INSERT INTO part set ?'
const params = {
name: name,
price: price,
mj_proportion: MJProportion,
protein_proportion: proteinProportion,
calcium_proportion: calciumProportion,
phosphorus_proportion: phosphorusProportion
}
// 执行sql语句
conn.query(sql, params, (err1, data1) => {
// 判断sql是否执行失败
if (err1) {
res.send({
status: 400,
msg: err1.message
})
} else if (data1.affectedRows !== 1){
// 判断数据是否插入成功 看affectedRows的值是否为1,不为1则写入失败
res.send({
status: 400,
msg: '数据写入失败'
})
} else {
// 否则写入成功 返回客户端
res.send({
status: 200,
msg: '新增成功'
})
}
})
}
})
})
router.delete("/deletePartById/:id", (req, res) => {
const id = String(req.params.id)
const sql = `delete from part where id = '${id}'`
conn.query(sql, (err, data) => {
if (err) {
res.send({
status: 400,
msg: '查询语句执行异常'
})
} else if (data.affectedRows !== 1) {
// affectedRows不为1则执行失败
res.send({
status: 400,
msg: '数据删除失败'
})
} else {
res.json({
status: 200,
msg: '数据删除成功',
})
}
})
})
router.put("/updatePart/:id", (req, res) => {
const id = String(req.params.id)
const { price, MJProportion, proteinProportion, calciumProportion, phosphorusProportion } = req.body
const params = {
price: price,
mj_proportion: MJProportion,
protein_proportion: proteinProportion,
calcium_proportion: calciumProportion,
phosphorus_proportion: phosphorusProportion,
}
// 方法一:
// const sql = 'update user set ? where id = ?'
// db.query(sql, [params, id], (err, data) => {
// 方法二:
const sql = `update part set ? where id = '${id}'`
conn.query(sql, params, (err, data) => {
if (err) {
res.send({
status: 400,
msg: err.message
})
} else if (data.affectedRows !== 1){
res.send({
status: 400,
msg: '修改失败!'
})
} else {
res.json({
status: 200,
msg: '修改成功!'
})
}
})
})
module.exports = router;
router.post("/addScheme",(req,res) => {
const {name, description, list} = req.body
const sql = `select * from scheme where name = '${name}'`
pool.query(sql, (err, result) => {
if (err) {
res.send({
status: 400,
msg: err.message
})
} else if (result.length > 0) {
res.json({
status: 400,
msg: '当前配方已存在!',
data: result
})
} else {
const insertSql = `INSERT INTO scheme set ?`
pool.query(insertSql, {name, description}, (err1, result1) => {
if (err1) {
res.json({
status: 404,
msg: err.message
});
} else if (result1.affectedRows !== 1){
res.send({
status: 400,
msg: '数据写入失败'
})
} else {
// 批量插入
const insertSQL = "INSERT INTO scheme_detail(scheme_id, part_id, part_weight, part_price) VALUES ?"
const schemeList = []
list.forEach(item => {
schemeList.push([
result1.insertId,
item.part_id,
item.part_weight,
item.part_price,
])
})
pool.query(insertSQL, [schemeList], (err2, data2) => {
if (err2) {
res.json({
status: 404,
msg: err2.message
});
}
res.json({
status: 200,
msg: '新增成功!',
data: data2
})
})
}
})
}
})
})
router.put("/updateScheme/:id", (req, res) => {
const id = String(req.params.id)
const {name, description, list} = req.body
const sql = `update scheme set ? where id = '${id}'`
pool.query(sql, { name, description }, (err, data) => {
if (err) {
res.send({
status: 400,
msg: err.message
})
} else if (data.affectedRows !== 1){
res.send({
status: 400,
msg: '修改失败!'
})
} else {
// 批量更新方案一:循环数据逐条进行更新或插入
// 批量更新方案二:将原有的数据全部清除,再重新全部插入
// 批量更新方案三:通过SQL直接修改
const insertSQL = "replace into scheme_detail (id, scheme_id, part_id, part_weight, part_price) values ?;"
const insertSQL1 = "INSERT INTO scheme_detail (id, scheme_id, part_id, part_weight, part_price) VALUES ? " +
"ON DUPLICATE KEY UPDATE id=values(id),scheme_id=values(scheme_id),part_weight=values(part_weight),part_price=values(part_price);"
const schemeList = []
list.forEach(item => {
schemeList.push([
item.id,
id,
item.part_id,
item.part_weight,
item.part_price,
])
})
pool.query(insertSQL1, [schemeList], (err2, data2) => {
if (err2) {
res.json({
status: 404,
msg: err2.message
});
}
res.json({
status: 200,
msg: '修改成功!',
data: data2
})
})
}
})
})
参考地址1