1、数据库:
server端:数据存在
client端:管理工具,node
mysql内有两个单位:
库:类似文件夹,容纳表
表:存储数据
行:一条数据
列(字段,域):一个数据项
主键:数据的唯一标识符。唯一的,操作性能高
Nodejs原生不支持mysql
2、SQL
1)增删改查
关键字大写
库名,表名,字段加反引号
分号结尾
增:INSERT
INSERT INTO 表 (字段列表)VALUES(值列表)
INSERT INTO `user` (`id`,`user`,`pwd`) VALUES(0,'aa','1234');
删:DELETE
改:UPDATE
查:SELECT
SELECT 内容 FROM 表名; 选取查询所有数据
const sql = require('mysql') //连接 //服务器、用户名、密码、库 let db = sql.createConnection({ host: 'localhost', user: 'root', password: '123', database: 'person' //还可以配置不同于3306的端口 port }) //数据库操作是非常典型的异步操作 //查询 //SQL语句,回调 db.query("SELECT * FROM `user_table`",(err,data)=>{ if(err){ console.log('sth goes wrong'+err) }else{ console.log(JSON.stringify(data)) } })
2、简单案例:
在进行程序设计之前首先设计数据字典
结合数据库完成相应服务器功能
const express = require('express') const static = require("express-static") const cp = require('cookie-parser') const cs = require('cookie-session') const bp = require('body-parser') const multer = require('multer') const ce = require('consolidate') const sql=require('mysql') //建立连接池 const db=sql.createPool({ host:'localhost', user:'root', password:'123', database:'blog' }) //构建服务器 let server = express() //服务器监听 server.listen(8080, function () { console.log('server is running') }) //解析cookie server.use(cp('abc321'))//秘钥 //使用session let keys = [] for (let i = 0; i < 1000; i++) { keys.push('keys_' + Math.random())//生成秘钥 } server.use(cs({ name: 'sess', keys: keys, maxAge: 30 * 3600 * 1000 })) //处理post数据 server.use(bp.urlencoded({ extended: false }))//不使用扩展模式,解析url数据 server.use(multer({ dest: './www/upload' }).any()) //配置模板引擎 server.set('view engine','html')//修改server全局配置,修改视图引擎为html //确认模板位置 server.set('views','./template') //确认所使用的模板引擎 server.engine('html',ce.ejs) server.get('/',(req,res)=>{ db.query("SELECT * FROM banner",(err,data)=>{ if(err){ //响应状态码 res.status(500).send('wrong:'+err).end() }else{ console.log(data) res.render('index.ejs',{banners:data}) } }) }) //处理静态请求 server.use(static('./www'))
//模板部分 <html> <head> <title>智能社-http://www.zhinengshe.com</title> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta charset="UTF-8"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="renderer" content="webkit"> <meta content="yes" name="apple-mobile-web-app-capable"> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0"> <meta name="description" content=" "> <meta name="keywords" content=""> <meta name="format-detection" content="telephone=no"> <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate"> <meta http-equiv="Pragma" content="no-cache"> <meta http-equiv="Expires" content="0"> <link href="css/base.css" rel="stylesheet" type="text/css"> <link href="css/index.css" rel="stylesheet" type="text/css"> <script src="js/font.js"></script> <script type="text/javascript" src="js/jquery-1.7.2.js"></script> <script type="text/javascript" src="js/swipe.js"></script> <script> $(function () { var mySwipe = Swipe($('.banner')[0], { auto: 2000, continuous: true, stopPropation: true, callback: function (index, element) { $('.banner ol li').removeClass('active'); $('.banner ol li').eq(index).addClass('active'); } }); }); </script> </head> <body> <div class="nav"> <ul> <li class="active"><a href="javascript:;">首页</a></li> <li><a href="javascript:;">关注</a></li> <li><a href="javascript:;">栏目</a></li> </ul> </div> <div class="content"> <div class="banner"> <ul class="clearfix"> <% for(var i=0;i<banners.length;i++){ %> <li> <img src="<%= banners[i].src %>" alt="" /> <div class="text-box"> <h2><%= banners[i].title %></h2> <p><%= banners[i].sub_title %></p> </div> </li> <% } %> </ul> <ol> <li class="active"></li> <li></li> <li></li> </ol> </div> <div class="newsList"> <ul> <%for(let i=0;i<articles.length;i++){%> <li> <a href="/article?id=<%= articles[i].ID%>"><!-- 传参 --> <h2><%=articles[i].title%></h2> <p><%=articles[i].summary%></p> </a> </li> <%}%> </ul> </div> </div> <div class="foot-btn"> <ul> <li class="home"><a href="index.html"></a></li> <li class="write"><a href="javascript:;"></a></li> <li class="my"><a href="mydoc.html"></a></li> </ul> </div> </body> </html>
//服务器部分
const express = require('express')
const static = require("express-static")
const cp = require('cookie-parser')
const cs = require('cookie-session')
const bp = require('body-parser')
const multer = require('multer')
const ce = require('consolidate')
const sql=require('mysql')
//建立连接池
const db=sql.createPool({
host:'localhost',
user:'root',
password:'123',
database:'blog'
})
//构建服务器
let server = express()
//服务器监听
server.listen(8080, function () {
console.log('server is running')
})
//解析cookie
server.use(cp('abc321'))//秘钥
//使用session
let keys = []
for (let i = 0; i < 1000; i++) {
keys.push('keys_' + Math.random())//生成秘钥
}
server.use(cs({
name: 'sess',
keys: keys,
maxAge: 30 * 3600 * 1000
}))
//处理post数据
server.use(bp.urlencoded({ extended: false }))//不使用扩展模式,解析url数据
server.use(multer({ dest: './www/upload' }).any())
//配置模板引擎
server.set('view engine','html')//修改server全局配置,修改视图引擎为html
//确认模板位置
server.set('views','./template')
//确认所使用的模板引擎
server.engine('html',ce.ejs)
server.get('/',(req,res,next)=>{
db.query("SELECT * FROM banner",(err,data)=>{
if(err){
//响应状态码
res.status(500).send('wrong:'+err).end()
}else{
res.banners=data
next()
}
})
})
server.get('/',(req,res,next)=>{
console.log(res.banners)
db.query("SELECT ID,title,summary FROM article",(err,data)=>{
if(err){
//响应状态码
res.status(500).send('wrong:'+err).end()
}else{
res.articles=data
next()
}
})
})
server.get('/',(req,res)=>{
console.log(res.banners)
db.query("SELECT title,summary FROM article",(err,data)=>{
res.render('index.ejs',{banners:res.banners,articles:res.articles})
})
})
server.get('/article',(req,res)=>{
res.render('conText.ejs',{})
})
//处理静态请求
server.use(static('./www'))
数据库更新语法:
UPDATE 表名 SET 字段=值 WHERE 条件
完整的博客小案例
const express = require('express') const static = require("express-static") const cp = require('cookie-parser') const cs = require('cookie-session') const bp = require('body-parser') const multer = require('multer') const ce = require('consolidate') const sql = require('mysql') const timeMod = require('./libs/common') //建立连接池 const db = sql.createPool({ host: 'localhost', user: 'root', password: '123', database: 'blog' }) //构建服务器 let server = express() //服务器监听 server.listen(8080, function () { console.log('server is running') }) //解析cookie server.use(cp('abc321'))//秘钥 //使用session let keys = [] for (let i = 0; i < 1000; i++) { keys.push('keys_' + Math.random())//生成秘钥 } server.use(cs({ name: 'sess', keys: keys, maxAge: 30 * 3600 * 1000 })) //处理post数据 server.use(bp.urlencoded({ extended: false }))//不使用扩展模式,解析url数据 server.use(multer({ dest: './www/upload' }).any()) //配置模板引擎 server.set('view engine', 'html')//修改server全局配置,修改视图引擎为html //确认模板位置 server.set('views', './template') //确认所使用的模板引擎 server.engine('html', ce.ejs) server.get('/', (req, res, next) => { db.query("SELECT * FROM banner", (err, data) => { if (err) { //响应状态码 res.status(500).send('wrong:' + err).end() } else { res.banners = data next() } }) }) server.get('/', (req, res, next) => { console.log(res.banners) db.query("SELECT ID,title,summary FROM article", (err, data) => { if (err) { //响应状态码 res.status(500).send('wrong:' + err).end() } else { res.articles = data next() } }) }) server.get('/', (req, res) => { console.log(res.banners) db.query("SELECT title,summary FROM article", (err, data) => { res.render('index.ejs', { banners: res.banners, articles: res.articles }) }) }) server.get('/article', (req, res) => { if (req.query.id) { if (req.query.act == 'like') { db.query(`UPDATE article SET likes=likes+1 WHERE ID=${req.query.id}`, (err, data) => { if (err) { res.status(500).send('sth is wrong' + err).end() } else { //显示文章 db.query(`SELECT * FROM article WHERE ID=${req.query.id}`, (err, data) => { if (err) { res.status(500).send('文章存在故障').end() } else { if (data.length == 0) {//确认文章不为空 res.status(404).send('文章不存在').end() } else { res.status(200) let thisData = data[0] thisData.date = timeMod.toDate(thisData.post_time) thisData.content = thisData.content.replace(/^/gm, '<p>').replace(/$/gm, '</p>') res.render('conText.ejs', { //使用正则为正文添加段落标签 thisArticle: thisData }) } } } ) } }) } else { db.query(`SELECT * FROM article WHERE ID=${req.query.id}`, (err, data) => { if (err) { res.status(500).send('文章存在故障').end() } else { if (data.length == 0) {//确认文章不为空 res.status(404).send('文章不存在').end() } else { res.status(200) let thisData = data[0] thisData.date = timeMod.toDate(thisData.post_time) thisData.content = thisData.content.replace(/^/gm, '<p>').replace(/$/gm, '</p>') res.render('conText.ejs', { //使用正则为正文添加段落标签 thisArticle: thisData }) } } } ) } } else { res.status(404).send('文章不存在').end() } }) //处理静态请求 server.use(static('./www'))