上一篇寫到了安裝 mysql,基本的 mysql 的命令行操作,以及使用 Node.js 連接 mysql 數(shù)據(jù)庫,今天這篇使用 koa 來操作 mysql,實(shí)現(xiàn)基本的增刪改查操作。
在上一篇新建的項(xiàng)目下,新建一個server目錄,表示這是服務(wù)端提供給頁面的接口服務(wù),然后在新建一個static目錄用來放前端的html js css等靜態(tài)資源文件,這個static目錄也可以是采用模板,比如pug等,也可以是前端經(jīng)過webpack打包之后的使用react或者vue框架開發(fā)的頁面,這里我直接是寫的最原始的html頁面,原生js操作頁面交互,沒有使用任何庫,因?yàn)楸疚牡闹攸c(diǎn)不在前端,而是操作mysql,所以使用最簡單,最原始的前端方式。下面進(jìn)入正題。
前端頁面部分
static目錄下新建一個index.html,這里面主要是調(diào)用接口,根據(jù)返回的數(shù)據(jù)顯示到頁面上,出于簡單考慮,直接將 js 的操作和 css 樣式全部寫到 index.html 中,請求使用的原生的fetch請求,下面是源碼:
// static/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>koa+mysql實(shí)現(xiàn)增刪改查操作</title>
<style>
html *{
padding:0;
margin:0;
border:0;
}
body{
position: relative;
height: 100%;
}
body div{
box-sizing: border-box;
}
input{
border:1px solid #66cded;
line-height: 32px;
font-size: 14px;
margin-bottom: 20px;
padding: 0 5px;
}
button{
border: 1px solid #3eacff;
background: #3eacff;
color:#fff;
font-size: 14px;
line-height: 30px;
padding:5px 10px;
margin-left: 50px;
}
hr{
border-bottom: 1px solid #ccc;
margin: 20px 0;
}
a{
color: #3eacff;
background: transparent;
text-decoration: none;
outline: none;
cursor: pointer;
}
a:hover{
color: #0c8cee;
}
#app{
width: 1200px;
margin: 0 auto;
padding-top: 20px;
}
.title{
font-weight: bold;
color: rgba(0,0,0,.85);
font-size: 16px;
}
.table-row{
border-collapse: collapse;
width: 100%;
}
.table-row thead tr{
background: #e4f3ff;
color:rgba(0,0,0,.85);
}
.table-row td{
border: 1px solid #ccc;
padding: 10px 20px;
text-align: center;
}
.mr15{
margin-right: 15px;
}
.mb15{
margin-bottom: 15px;
}
.modal{
position: fixed;
left: 0;
top:0;
right: 0;
bottom: 0;
width: 100%;
height: 100%;
background: rgba(55,55,55,.6);
}
.modal-form{
position: absolute;
background: #fff;
padding: 40px 20px;
top: 50%;
left: 50%;
width: 400px;
color: #000;
margin-left: -200px;
margin-top: -100px;
text-align: center;
}
#close{
position: absolute;
top: 0;
right: 0;
color: #000;
background: #fff;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<div id="app">
<p class="mb15 title">添加數(shù)據(jù)</p>
<form>
<p><label for="name">name: </label><input type="text" id="name" /></p>
<p><label for="status">status: </label><input type="text" id="status" /></p>
<p><button id="addBtn">添加數(shù)據(jù)</button></p>
</form>
<hr />
<p class="mb15 title">顯示表的數(shù)據(jù)</p>
<div id="showData"></div>
<hr />
<p class="mb15 title">顯示一條數(shù)據(jù)的詳情信息</p>
<div id="detail"></div>
<div id="modal" style="display: none;" class="modal">
<form class="modal-form">
<p><label for="name">name: </label><input type="text" id="edit_name" /></p>
<p><label for="status">status: </label><input type="text" id="edit_status" /></p>
<p><button id="edit_btn">提交修改</button></p>
<button id="close">關(guān)閉</button>
</form>
</div>
</div>
<script>
var showData = document.getElementById('showData');
var addBtn = document.getElementById('addBtn');
var detail = document.getElementById('detail');
var edit_btn = document.getElementById('edit_btn');
var modal = document.getElementById('modal');
var close = document.getElementById('close');
var ID = '';
function getList(){
fetch('/getList')
.then((res) => {
return res.json();
})
.then((data) => {
let str = '<table class="table-row" id="tableRow"><thead><tr><td>ID</td><td>name</td><td>status</td><td>操作</td></tr></thead><tbody>';
data.data.forEach(item => {
str += '<tr><td>' + item.id + '</td><td>' + item.name + '</td><td>' + item.status + '</td><td><a href="javascript:;" class="detail mr15" data-id='+item.id+'>詳情</a><a href="javascript:;" class="edit mr15" data-item='+JSON.stringify(item)+'>編輯</a><a href="javascript:;" class="delete" data-id='+item.id+'>刪除</a></td></tr>';
});
str += '</tbody></table>';
showData.innerHTML = str;
});
}
getList();
function add(){
var name = document.getElementById('name').value;
var status = document.getElementById('status').value;
var params = {
name: name,
status: status
}
fetch('/add', {
method: 'POST',
body: JSON.stringify(params)
})
.then((res) => {
return res.json()
})
.then((data) => {
if(data.code === 200){
getList();
}
})
}
addBtn.onclick = function(e){
e.preventDefault();
add();
};
function deleteData(id){
fetch('/delete', {
method: 'POST',
body: JSON.stringify({id: id})
})
.then((res) => {
return res.json()
})
.then((data) => {
if(data.code === 200){
getList();
}
})
}
function getInfo(id){
fetch('/getInfo/'+id)
.then((res) => {
return res.json()
})
.then((resp) => {
var data = resp.data;
var str= 'ID 為'+ data.id+ '的詳細(xì)數(shù)據(jù)如下:'+'<br />';
if(resp.code == 200){
str += 'ID:'+ data.id + '<br />';
str += 'name:'+ data.name + '<br />';
str += 'status:'+ data.status + '<br />';
} else {
str += resp.message;
}
detail.innerHTML = str;
})
}
function updateData(id, name, status){
fetch('/update', {
method: 'POST',
body: JSON.stringify({id: id, name: name, status: status})
})
.then((res) => {
return res.json()
})
.then((data) => {
console.log(data);
modal.style.display = 'none';
if(data.code === 200){
getList();
}
})
}
showData.onclick = function(e){
var target = e.target.className;
var item = JSON.parse(e.target.getAttribute('data-item'));
if(target.indexOf('edit') > -1){
modal.style.display = 'block';
document.getElementById('edit_name').value = item.name;
document.getElementById('edit_status').value = item.status;
ID = item.id;
} else if(target.indexOf('delete') > -1){
const id = e.target.getAttribute('data-id');
deleteData(id);
} else if(target.indexOf('detail') > -1){
const id = e.target.getAttribute('data-id');
getInfo(id);
}
}
edit_btn.onclick = function(e){
e.preventDefault();
var edit_name = document.getElementById('edit_name').value;
var edit_status = document.getElementById('edit_status').value;
updateData(ID, edit_name, edit_status);
}
close.onclick = function(e){
e.preventDefault();
modal.style.display = 'none';
}
</script>
</body>
</html>
server端服務(wù)部分
安裝依賴庫,跑起服務(wù)
這里選用的 Node.js 框架是 koa,路由是koa-router,koa-static是 koa 靜態(tài)文件服務(wù)中間件,post 方式提交獲取參數(shù)使用 koa-body,需要安裝這些庫。沒安裝 mysql 的,也需要安裝。
npm i koa koa-router koa-static koa-body mysql -S
安裝完成之后可以安裝 nodemon,在每次修改代碼之后,無需重啟服務(wù):npm i nodemon -S
接下來在 server 目錄下新建一個 index.js,寫入如下代碼,然后運(yùn)行 nodemon server/index.js,先將服務(wù)跑起來:
// server/index.js
const Koa = require('koa');
const static = require('koa-static');
const app = new Koa();
const staticPath = '../static';
app.use(static(
join(__dirname, staticPath)
));
app.listen(4455);
console.log('listen at 4455');
可以看到頁面如下,還沒有數(shù)據(jù)填充:

獲取表數(shù)據(jù)
現(xiàn)在繼續(xù)完善 index.js,先獲取到表的數(shù)據(jù)。
server目錄下新建mysql_config.js,用來寫 mysql 的連接需要的 mysql 配置信息:
module.exports = {
mysql: {
host: 'localhost',
user: 'root',
password: '123456',
database: 'koa_test'
}
}
在新建一個db.js用來連接數(shù)據(jù)庫,因?yàn)閿?shù)據(jù)庫的讀取寫入也是異步的,代碼中先連接數(shù)據(jù)庫,獲取一個 mysql 的連接,然后使用 promise 封裝一下 query 操作,這樣后續(xù)我們可以使用await關(guān)鍵字來同步的寫代碼,異步獲取到結(jié)果,代碼如下:
// server/db.js
const mysql = require('mysql');
const config = require('./mysql_config');
const conn = mysql.createConnection(config.mysql);
conn.connect((err) => {
if(err){
throw err;
}
console.log('mysql 連接成功');
});
let query = (sql, params) => {
return new Promise((resolve, reject) => {
conn.query(sql, params, (error, result, fields) => {
if(error){
reject(error);
} else {
resolve(result);
}
})
})
}
//關(guān)閉連接
//conn.end();
module.exports = { conn, query};
接下來我們就讓頁面的數(shù)據(jù)表先顯示出來吧,在index.js中寫入如下代碼,我們直接上完整的代碼,不上代碼片段,以防看到的同學(xué)根據(jù)片段跑不起來服務(wù)。下面的代碼主要是koa-router路由配置,然后查詢數(shù)據(jù)表domian的數(shù)據(jù),sql 語句 await query('SELECT * FROM domain;'),:
// server/index.js
const Koa = require('koa');
const static = require('koa-static');
const Router = require('koa-router');
const { join } = require('path');
const { query } = require('./db');
const app = new Koa();
const router = new Router();
const staticPath = '../static';
app.use(static(
join(__dirname, staticPath)
));
app.use(router.routes()).use(router.allowedMethods());
router.get('/getList', async (ctx, next) => {
ctx.type = 'Content-Type: application/json;charset=utf-8';
let result = await query('SELECT * FROM domain;');
let list = [];
result.forEach(item => {
list.push({
id: item.id,
name: item.name,
status: item.status
})
});
console.log(list);
ctx.body = {
code: 200,
data: list,
message: 'getList success'
};
});
app.listen(4455);
console.log('listen at 4455');
nodemon 會根據(jù)文件變化重新啟動服務(wù),現(xiàn)在我們刷新頁面,可以看到數(shù)據(jù)表出來了:

添加一條數(shù)據(jù)到表中
數(shù)據(jù)列表我們拿到了,現(xiàn)在添加一條數(shù)據(jù)到表里,使用koa-body,獲取post的body參數(shù),sql語句是這樣的await query('INSERT INTO domain SET ?', JSON.parse(postData)); 這是 mysql 模塊的語法。index.js 向表中添加數(shù)據(jù)的完整代碼如下:
//server/index.js
const Koa = require('koa');
const static = require('koa-static');
const Router = require('koa-router');
const koaBody = require('koa-body');
const { join } = require('path');
const { query } = require('./db');
const app = new Koa();
const router = new Router();
const staticPath = '../static';
app.use(koaBody());
app.use(static(
join(__dirname, staticPath)
));
app.use(router.routes()).use(router.allowedMethods());
router.get('/getList', async (ctx, next) => {
ctx.type = 'Content-Type: application/json;charset=utf-8';
let result = await query('SELECT * FROM domain;');
let list = [];
result.forEach(item => {
list.push({
id: item.id,
name: item.name,
status: item.status
})
});
console.log(list);
ctx.body = {
code: 200,
data: list,
message: 'getList success'
};
});
router.post('/add', async (ctx, next) => {
const postData = ctx.request.body;
console.log('postData:',JSON.parse(postData));
ctx.type = 'Content-Type: application/json;charset=utf-8';
await query('INSERT INTO domain SET ?', JSON.parse(postData));
ctx.body = {
code: 200,
data: [],
message: 'add success'
};
})
app.listen(4455);
console.log('listen at 4455');
現(xiàn)在我們在頁面上添加一條數(shù)據(jù),從列表中可以看到數(shù)據(jù)被添加進(jìn)去了:

修改表中的某一條數(shù)據(jù)
接下來我們修改數(shù)據(jù),sql 語句是這樣的:await query('UPDATE domain SET name = ?, status = ? WHERE id = ?;',[pdata.name, pdata.status, pdata.id]);,我們把剛剛添加的一條數(shù)據(jù)修改一下內(nèi)容,點(diǎn)頁面的編輯,彈出 modal 層來修改數(shù)據(jù),完整代碼如下:
// server/index.js
const Koa = require('koa');
const static = require('koa-static');
const Router = require('koa-router');
const koaBody = require('koa-body');
const { join } = require('path');
const { query } = require('./db');
const app = new Koa();
const router = new Router();
const staticPath = '../static';
app.use(koaBody());
app.use(static(
join(__dirname, staticPath)
));
app.use(router.routes()).use(router.allowedMethods());
router.get('/getList', async (ctx, next) => {
ctx.type = 'Content-Type: application/json;charset=utf-8';
let result = await query('SELECT * FROM domain;');
let list = [];
result.forEach(item => {
list.push({
id: item.id,
name: item.name,
status: item.status
})
});
console.log(list);
ctx.body = {
code: 200,
data: list,
message: 'getList success'
};
});
router.post('/add', async (ctx, next) => {
const postData = ctx.request.body;
console.log('postData:',JSON.parse(postData));
ctx.type = 'Content-Type: application/json;charset=utf-8';
await query('INSERT INTO domain SET ?', JSON.parse(postData));
ctx.body = {
code: 200,
data: [],
message: 'add success'
};
})
router.post('/update', async (ctx, next) => {
const postData = ctx.request.body;
console.log('update postData:', JSON.parse(postData));
const pdata = JSON.parse(postData);
await query('UPDATE domain SET name = ?, status = ? WHERE id = ?;',[pdata.name, pdata.status, pdata.id]);
ctx.type = 'Content-Type: application/json;charset=utf-8';
ctx.body = {
code: 200,
data: [],
message: 'update success'
}
})
app.listen(4455);
console.log('listen at 4455');
原始的顯示數(shù)據(jù),

現(xiàn)在修改數(shù)據(jù):

提交修改,可以看出數(shù)據(jù)表中的數(shù)據(jù)確實(shí)被修改了:

刪除一條數(shù)據(jù)
現(xiàn)在我們把剛修改的數(shù)據(jù)給刪除吧,sql 語句是這樣的:await query('DELETE FROM domain where id=' + JSON.parse(postData).id);,完整代碼如下:
// server/index.js
const Koa = require('koa');
const static = require('koa-static');
const Router = require('koa-router');
const koaBody = require('koa-body');
const { join } = require('path');
const { query } = require('./db');
const app = new Koa();
const router = new Router();
const staticPath = '../static';
app.use(koaBody());
app.use(static(
join(__dirname, staticPath)
));
app.use(router.routes()).use(router.allowedMethods());
router.get('/getList', async (ctx, next) => {
ctx.type = 'Content-Type: application/json;charset=utf-8';
let result = await query('SELECT * FROM domain;');
let list = [];
result.forEach(item => {
list.push({
id: item.id,
name: item.name,
status: item.status
})
});
console.log(list);
ctx.body = {
code: 200,
data: list,
message: 'getList success'
};
});
router.post('/add', async (ctx, next) => {
const postData = ctx.request.body;
console.log('postData:',JSON.parse(postData));
ctx.type = 'Content-Type: application/json;charset=utf-8';
await query('INSERT INTO domain SET ?', JSON.parse(postData));
ctx.body = {
code: 200,
data: [],
message: 'add success'
};
})
router.post('/update', async (ctx, next) => {
const postData = ctx.request.body;
console.log('update postData:', JSON.parse(postData));
const pdata = JSON.parse(postData);
await query('UPDATE domain SET name = ?, status = ? WHERE id = ?;',[pdata.name, pdata.status, pdata.id]);
ctx.type = 'Content-Type: application/json;charset=utf-8';
ctx.body = {
code: 200,
data: [],
message: 'update success'
}
})
router.post('/delete', async (ctx, next) => {
ctx.type = 'Content-Type: application/json;charset=utf-8';
const postData = ctx.request.body;
console.log('delete postData:', JSON.parse(postData));
await query('DELETE FROM domain where id=' + JSON.parse(postData).id);
ctx.body = {
code: 200,
data: [],
message: 'delete success'
}
});
app.listen(4455);
console.log('listen at 4455');
現(xiàn)在點(diǎn)擊列表刪除剛添加的那一條數(shù)據(jù),可以看到數(shù)據(jù)被刪除了:

獲取某一條數(shù)據(jù)的詳細(xì)信息
最后我們來獲取某一條數(shù)據(jù)的詳細(xì)信息吧,sql 語句是這樣的:await query('SELECT * FROM domain WHERE id = ?;', ctx.params.id),完整代碼如下:
// server/index.js
const Koa = require('koa');
const static = require('koa-static');
const Router = require('koa-router');
const koaBody = require('koa-body');
const { join } = require('path');
const { query } = require('./db');
const app = new Koa();
const router = new Router();
const staticPath = '../static';
app.use(koaBody());
app.use(static(
join(__dirname, staticPath)
));
app.use(router.routes()).use(router.allowedMethods());
router.get('/getList', async (ctx, next) => {
ctx.type = 'Content-Type: application/json;charset=utf-8';
let result = await query('SELECT * FROM domain;');
let list = [];
result.forEach(item => {
list.push({
id: item.id,
name: item.name,
status: item.status
})
});
console.log(list);
ctx.body = {
code: 200,
data: list,
message: 'getList success'
};
});
router.post('/add', async (ctx, next) => {
const postData = ctx.request.body;
console.log('postData:',JSON.parse(postData));
ctx.type = 'Content-Type: application/json;charset=utf-8';
await query('INSERT INTO domain SET ?', JSON.parse(postData));
ctx.body = {
code: 200,
data: [],
message: 'add success'
};
})
router.post('/update', async (ctx, next) => {
const postData = ctx.request.body;
console.log('update postData:', JSON.parse(postData));
const pdata = JSON.parse(postData);
await query('UPDATE domain SET name = ?, status = ? WHERE id = ?;',[pdata.name, pdata.status, pdata.id]);
ctx.type = 'Content-Type: application/json;charset=utf-8';
ctx.body = {
code: 200,
data: [],
message: 'update success'
}
})
router.post('/delete', async (ctx, next) => {
ctx.type = 'Content-Type: application/json;charset=utf-8';
const postData = ctx.request.body;
console.log('delete postData:', JSON.parse(postData));
await query('DELETE FROM domain where id=' + JSON.parse(postData).id);
ctx.body = {
code: 200,
data: [],
message: 'delete success'
}
});
router.get('/getInfo/:id', async (ctx, next) => {
ctx.type = 'Content-Type: application/json;charset=utf-8';
let result = await query('SELECT * FROM domain WHERE id = ?;', ctx.params.id);
console.log('詳情數(shù)據(jù):',result);
ctx.body = {
code: 200,
data: result[0],
message: 'getInfo success'
};
})
app.listen(4455);
console.log('listen at 4455');
點(diǎn)擊數(shù)據(jù)表中的一條數(shù)據(jù)詳情,然后顯示詳情到頁面:

最后,mysql 的基本操作就算完成了,到獲取詳情這里已經(jīng)是 index.js 的全部代碼了。
代碼調(diào)試
再說一下代碼調(diào)試,如果在寫代碼的過程中,遇到問題,如何調(diào)試呢。
前端頁面發(fā)起請求之后,node js代碼在接收到請求之后進(jìn)到斷點(diǎn)那里,這樣就可以調(diào)試了,具體調(diào)試方式就是,在啟動服務(wù)的時候加上--inspect-brk 參數(shù),然后打開chrome瀏覽器輸入:chrome://inspect/#devices,然后點(diǎn)擊頁面出現(xiàn)的Open dedicated DevTools for Node這個文字,會新打開一個chrome DevTools,這就跟瀏覽器的調(diào)試一樣的,server的代碼也會在Sources里面找到,下面我們演示一下:
1.首先在運(yùn)行命令node --inspect-brk server/index.js,可以看到如下信息:

2.瀏覽器輸入chrome://inspect/#devices,點(diǎn)擊Open dedicated DevTools for Node:

3.點(diǎn)擊之后會彈出如下的調(diào)試面板,然后在想要調(diào)試的地方打上斷點(diǎn)即可:

4.現(xiàn)在刷新跑服務(wù)的瀏覽器http://localhost:4455/,然后添加一條數(shù)據(jù),在上一步的調(diào)試面板中給add方法打上斷點(diǎn),可以看到代碼就進(jìn)來了,然后就一步步往下調(diào)試就可以了。

以上遇到問題最多的還是寫 mysql 語句,直接命令行操作 mysql 沒問題,主要是代碼操作就需要查 sql 的寫法,具體 mysql 的一些寫法可以上 npm 找到 mysql 模塊看一下。