接着上一篇完善数据库
一、建表
- user表
column | datatype | pk主建 | nn不为空 | Al自动增加 | Default |
---|---|---|---|---|---|
id | int | Y | Y | Y | |
username | varchar(20) | Y | |||
password | varchar(20) | Y | |||
realname | varchar(10) | Y |
- blog表
column | datatype | pk主建 | nn不为空 | Al自动增加 | Default |
---|---|---|---|---|---|
id | int | Y | Y | Y | |
title | varchar(50) | Y | |||
content | longtext | Y | |||
createtime | bigint(20) | Y | 0 | ||
author | varchar(20) | Y |
二、 Nodejs操作Mysql(小案例)
- 在项目中下载mysql插件
- 写程序
const mysql = require('mysql')
//创建连接
const con = mysql.createConnection({
host:'localhost',//本地地址
user:'您的mysql用户名',//用户名
password:'您的mysql密码',//密码
port:'您的端口号',//端口号
database:'node_blog'//数据库名称
})
//开始连接
con.connect()
//执行sql语句
const sql ='select * from user;'
//异步操作
con.query(sql,(err,result) => {
if (err) {
console.error(err)
return
}
console.log(result)
})
//关闭连接
con.end()
- 测试
三、将Nodejs连接数据库封装成工具
- 在原项目的src下创建conf文件夹并在该目录下创建conf.js文件
- 修改package.json配置
- 在conf.js文件中配置数据库参数
const env = process.env,NODE_ENV //获取环境参数 package.json dev
let MYSQL_CONF
//配置
if (env === "dev") {
MYSQL_CONF = {
host:'localhost',//本地地址
user:'root',//用户名
password:'123456',//密码
port:3306,//端口号
database:'node_blog'//数据库名称
}
}
if (evn === "production") {
MYSQL_CONF ={
//配置线上参数
}
}
module.exports = {
MYSQL_CONF
}
- 在src目录下创建db文件夹并在该目录下创建mysql.js文件
- 在mysql.js封装操作数据库的sql
const mysql = require('mysql')
const { MYSQL_CONF } = require('../conf/db')
//创建连接对象
const con = mysql.createConnection(MYSQL_CONF)
//开始连接
con.connect()
//统一执行sql的函数
function exec(sql) {
const promise = new Promise((resolve, reject) => {
con.query(sql, (err, result) => {
if (err) {
reject(err)//失败
return
}
resolve(result)//成功
})
})
return promise
}
module.exports = exec
四、API对接mysql
先将exec加载到controller文件夹中的blog.js和user.js
const { exec } = require('../db/mysql')
(1)博客列表
- 将原来写好返回的假数据删除,修改成对接数据库,返回真数据。
// controller/blog.js
const getList = (author,keyword) => {
/**
* 因为 author 和 keyword 的值不确定,因此需要添加 1=1
* (1)比如去掉 1=1时,如果 author 和 keyword 没有值,
* 此时 sql 语句:select * from blog where order by createtime desc;
* 报错 sql语句错误
*
* (2)比如去掉 where 1=1时,author 和 keyword 都存在,
* 此时sql语句:
* select * from blog and author ='${author}' and title like '%${keyword}%'
* 报错 sql语句错误
**/
let sql =`select * from blog where 1=1 `
if (author) {
sql += ` and author ='${author}' `
}
if (keyword) {
sql += ` and title like '%${keyword}%' `
}
sql += `order by createtime desc;`
//返回 promise
return exec(sql)
}
- 修改获取博客列表的路由接口
// router/blog.js
//获取博客列表
if (method === "GET" && req.path === "/api/blog/list") {
//获取请求数据
const author = req.query.author || ''
const keyword = req.query.keyword || ''
//去请求数据 (假数据)
// const listData = getList(author,keyword)
// return new SuccessModel(listData)
//去请求数据 (真数据)
const result = getList(author,keyword)
//此时返回是promise对象 而不是原先的直接返回的数据
return result.then(listData => {
return new SuccessModel(listData)
})
}
注意:此时路由层返回到上一层(app.js)是promise对象,不是原先直接返回数据,因此需要在转发路由,接收到返回数据的部分,修改接收数据的类型
- 修改app.js接收的数据类型
//处理 blog 路由 (对象是promise)
const blogResult = handleBlogRouter(req, res)
if (blogResult) {
blogResult.then(blogData => {
res.end(
JSON.stringify(blogData)
)
})
return
}
//处理 blog 路由 (对象时数据)
// const blogData = handleBlogRouter(req,res)
// if (blogData) {
// res.end(
// JSON.stringify(blogData)
// )
// return
// }
- 测试
(2) 博客详情与新建 - 博客详情
// controller/blog.js
const getDetail = (id) => {
//先返回假数据(格式正确)
// return [
// {
// id:1,
// title:'标题A',
// content:'内容A',
// createTime:1546610491112,
// author:'zhangsan'
// }
// ]
let sql = `select content from blogs where id=${id}`
return exec(sql)
}
//router/blog.js
//获取博客详情
if (method === "GET" && req.path === "/api/blog/detail") {
//去请求数据(假数据)
// const detail = getDetail(id)
// return new SuccessModel(detail)
const result = getDetail(id)
return result.then(detail => {
return new SuccessModel(detail)
})
}
-
测试
-
博客新建
// controller/blog.js
const newBlog = (blogData ={}) => {
//blogData 是一个博客对象,包含 title content author 属性
const title = blogData.title
const content = blogData.content
const author = blogData.author
const createTime = Date.now()
const sql = `insert into blogs (title, content, createtime, author)
values ('${title}', '${content}', ${createTime}, '${author}')`
return exec(sql).then(insertData => {
console.log(insertData)//打印出来看看返回什么信息
return {
id:insertData.insertId
}
})
}
//router/blog.js
//新增一篇博客
if (method === "POST" && req.path === "/api/blog/new") {
//获取post请求数据 (app.js中已经获取到了)
// const postData = req.body
// const id = newBlog(postData)
// return new SuccessModel(id)
req.body.author = 'zhangsan' //假数据,待开发登录时再改成真实数据
const postData = req.body
const result =newBlog(postData)
return result.then(id => {
new SuccessModel(id)
})
}
- 测试
(3)博客更新与删除
- 博客更新
// controller/blog.js
const updateBlog = (id,blogData ={}) => {
//id 就是要更新博客的 id
//blogData 是一个博客对象,包含 title content 属性
const content = blogData.content
const title = blogData.title
let sql = `update blogs set title='${title}', content='${content}' where id=${id}`
return exec(sql).then(updateData => {
console.log(updateData)
if (updateData.affectedRows > 0) {
return true
}
return false
})
}
//router/blog.js
//更新一篇博客
if (method === "POST" && req.path === "/api/blog/update") {
//获取post请求数据 (app.js中已经获取到了)
// const postData = req.body
// const result = updateBlog(id, postData)
// if (result) {
// return new SuccessModel(result)
// }
// return new ErrorModel('更新博客失败')
const postData = req.body
const result = updateBlog(id, postData)
return result.then(val => {
if (val) {
return new SuccessModel(val)
}else{
return new ErrorModel('更新博客失败')
}
})
}
- 测试
- 博客删除
// controller/blog.js
const delBlog = (id,author) => {
//id 就是要删除博客的 id
let sql = `delete from blogs where id=${id} and author='${author}';`
return exec(sql).then(delData => {
console.log(delData)
if (delData.affectedRows > 0) {
return true
}
return false
})
}
//router/blog.js
if (req.method === "POST" && req.path === "/api/blog/del") {
// const result = delBlog(id)
// if (result) {
// return new SuccessModel(result)
// }
// return new ErrorModel('删除博客失败')
author = 'zhangsan' //假数据,待开发登录时再改成真实数据
const result =delBlog(id,author)
return result.then(val => {
if (val) {
return new SuccessModel(val)
}else {
return new ErrorModel('删除博客失败')
}
})
}