Node.js使用MySQL
阿新 • • 發佈:2020-12-07
資料庫簡介
資料庫(Database)是按照資料結構來組織、儲存和管理資料的倉庫。
為什麼需要用到資料庫?我們之前寫服務端的時候,資料都是儲存在本地檔案中做持久化儲存的,對於少量的資料還可以,讀寫速度也能接收,但是一旦資料量大起來,讀檔案的操作將會非常慢,讀了檔案之後還要對檔案中的資訊進行檢索,這樣就顯得非常低效,查詢一個數據要等待幾十秒甚至上百秒這顯然是不能接受的,這時就需要使用資料了系統才儲存資料了,那有人問為什麼資料庫存資料就比使用檔案儲存資料查詢速度要快呢?因為資料庫系統裡面使用了很多資料結構和演算法來優化檢索,這是檔案沒法比擬的。
這篇文章只講MySQL在Node.js中的使用,主要根據下面的結構來講。
- MySQL安裝
- 基礎的SQL語句
- Node.js中使用Mysql
- todos案例
資料庫安裝
官網:
下載:
集成了MySQL的第三方工具:XAMPP、PHPstudy
MySQL的特點
資料以表格的形式出現,表格中每一行表示一組資料,表格中每一列表示某組資料對應的欄位(屬性),若干這樣的行和列就組成了一張表,若干個表格組成一個庫。
MySQL 服務就是維護了若干個這樣的庫。
基礎SQL語句
mysql -uroot -p密碼 // 連線資料庫 show databases; // 檢視所有資料庫 use 資料庫名; // 選擇要操作的資料庫 create database 資料庫名; // 建立新的資料庫 insert into 表名 (欄位1,欄位2,...欄位N) values (值1,值2,...值N); // 插入資料,注意如果值為字串型別則必須使用單引號或者雙引號進行包裹
Node.js中使用MySQL
在node.js中我們可以使用mysql2這個模組來操作資料庫。
參考程式碼
(async function () { const mysql = require('mysql2/promise'); const connection = await mysql.createConnection({ host: '127.0.0.1', user: 'root', password: 'root', database: 'miaov' }); /** * arr返回一個數組,第一個陣列是記錄的值,第二個陣列是記錄中包含的欄位的資訊 */ // let arr = await connection.query('select * from users'); // console.log(arr); // 陣列的解構操作,解構陣列中的第一項 let [users] = await connection.query("select * from users"); console.log(users); users.forEach(item => { console.log(item); }) })()
我們使用的時候之所以要包裝一層自呼叫函式,這是因為這裡使用的是promise版本的mysql2,我們需要使用async/await來等待非同步操作,所以我們需要套一層函式並在函式前面加上async
關鍵字。
todos案例
參考程式碼
app.js
const { create } = require('domain');
(async function(){
const Koa = require('koa');
const Static = require('koa-static-cache');
const Router = require('koa-router');
const BodyParser = require('koa-bodyparser');
const Mysql = require('mysql2/promise');
const fs = require('fs');
const app = new Koa()
// 建立資料庫連線
const connection = await Mysql.createConnection({
host: '127.0.0.1',
user: 'root',
password: 'root',
database: 'todos'
})
// 使用bodyParser處理正文資料
app.use(BodyParser())
// 託管靜態資源
app.use(Static('./static', {
prefix: '/public',
gzip: true
}))
const router = new Router();
router.get('/', async ctx=>{
ctx.body = await fs.readFileSync('./static/index.html').toString();
})
router.get('/getList', async ctx=>{
const [res] = await connection.query('select * from todos');
console.log(res);
ctx.body = res;
})
router.post('/add', async ctx=> {
let {title} = ctx.request.body || "";
console.log(title);
if(!title.trim()) {
// 為空的情況
ctx.body = {code: 0, data: 'title不能為空!'}
}else {
const [res] = await connection.query(`insert into todos (title, done) values ('${title}', 0)`)
console.log(res);
ctx.body = {code:1 , data: '新增資料成功!'}
}
})
app.use(router.routes());
app.listen(80, ()=>{
console.log("koa server listen: 0.0.0.0:80")
})
})()
/static/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
</head>
<body>
<h1>Todos</h1>
<hr />
<div id="app">
<input type="text" placeholder="請輸入任務..." v-model="taskValue">
<input type="button" value="新增" @click="handleAddTask">
<ul>
<li v-for="(item, index) in list">
<span>{{item.id}}</span>
<span>{{item.title}}</span>
<button>刪除</button>
</li>
</ul>
</div>
<script>
new Vue({
el: '#app',
data: {
list: [],
taskValue: ""
},
methods: {
// 獲取todos列表資料
getList(){
fetch('/getList').then(res=>res.json())
.then(response=>{
this.list = response;
console.log(this.list)
})
},
// 監聽新增todos任務事件
handleAddTask(){
console.log(this.taskValue);
if(!this.taskValue.trim()) {
alert('任務標題不能為空!');
}else {
fetch('/add', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({title: this.taskValue})
}).then(res=>res.json())
.then(response=>{
console.log(response);
if(response.code) {
this.taskValue = "";
this.getList();
}
})
}
}
},
created(){
console.log("created...");
this.getList();
}
})
</script>
</body>
</html>