安裝mysql
npm install mysql
創(chuàng)建管理mysql文件
創(chuàng)建dbManager.js
引入mysql
// 引入mysql
const mysql = require("mysql");
創(chuàng)建鏈接池
// 建立一個連接池
const db = mysql.createPool({
// 主機(jī)地址 (默認(rèn):localhost), 本地的只能默認(rèn)為127.0.0.1
host: "127.0.0.1", // 數(shù)據(jù)庫的IP地址(本地的或者是云服務(wù)器的都可以)
port: "3306",
// 用戶名
user: "root",
// 密碼
password: "12345678",
// 指定要操作哪個數(shù)據(jù)庫
database: "lulu",
// 連接字符集(默認(rèn):‘UTF8_GENERAL_CI’,注意字符集的字母都要大寫)
charset: "UTF8_GENERAL_CI"
});
導(dǎo)出數(shù)據(jù)庫連接池對象
module.exports = db;
使用mysql
在需要使用數(shù)據(jù)的地方引入dbManager
// 引入
const db = require("./dbManager");
創(chuàng)建表
數(shù)據(jù)庫表, 一般是在添加數(shù)據(jù)的時候創(chuàng)建, 添加數(shù)據(jù)步驟如下:
- 判斷有沒有該表, 如果有, 直接添加;
- 沒有該表進(jìn)行創(chuàng)建
- 創(chuàng)建完成之后再添加該數(shù)據(jù)
代碼如下
apiRouter.post('/add', (req,res) => {
const {username, password} = req.body;
const hashedPassword = bcrypt.hash(password, 10);
// 驗證表是否存在
const table = 'user_info';
const checkSql = `select 1 from ${table} limit 1`;
db.query(checkSql, error => {
if(error) {
// 如果不存在收壕, 就創(chuàng)建表
let creatSql = `
create table user_info
(
id int(20) not null AUTO_INCREMENT,
name varchar(20),
pwd varchar(20) not null,
age int(4),
PRIMARY KEY (id)
)
`
// 如果表不存在就建立這個表妓灌,那么可以直接用 create table if not exists tablename 這樣的指令來建立,不需要先去查詢表是否存在蜜宪。
db.query(creatSql, (error, results) => {
if(error){
// 如果創(chuàng)建失敗就返回錯誤
console.log(error)
res.status(500).send('error occurred while creating table')
} else {
// 如果創(chuàng)建成功就插入數(shù)據(jù)
insertAction();
}
})
} else {
// 如果已經(jīng)存在虫埂, 則直接插入數(shù)據(jù)
insertAction();
}
// 插入數(shù)據(jù)方法
function insertAction(){
// 插入數(shù)據(jù), 如果id是自增屬性, 則要對應(yīng)名稱插入值
let insertSql = `
insert into ${table}
(name, pwd, age)
values
(${username}, '', 0)
`;
// 插入數(shù)據(jù)
// let insertSql = `insert into user_info values (${id}, ${name}, '', 0)`;
db.query(insertSql, (error, results) => {
if(error){
// 創(chuàng)建失敗
res.status(500).send('error occurred while creating account')
} else {
// 創(chuàng)建成功
res.status(201).send('account created successfully')
}
})
}
})
})
當(dāng)然上面的insertAction方法也可以如下寫法
// 插入數(shù)據(jù)方法
function insertAction(){
// 插入數(shù)據(jù), 如果id是自增屬性圃验, 則要對應(yīng)名稱插入值
let insertSql = `
insert into ${table}
(name, pwd, age)
values
(?, ?, ?)
`;
const values = ['張三', '123', null]
db.query(insertSql, values, (error, results) => {
if(error){
// 創(chuàng)建失敗
res.status(500).send('error occurred while creating account')
} else {
// 創(chuàng)建成功
res.status(201).send('account created successfully')
}
})
}
查詢
apiRouter.get('/login', (req,res) => {
const {username, password} = req.query;
if(!username || !phoneReg.test(username)) {
res.send({code: 1, ErrorMsg: '請?zhí)顚懻_的用戶名掉伏!'});
return;
}
if(!password || password.length < 5) {
res.send({code: 1, ErrorMsg: '請輸入密碼!'});
return;
}
db.query('SELECT * FROM user_info WHERE username = ?', [username], (error, results) => {
if (error) {
res.send({code: 1, ErrorMsg: error.code });
} else if (results.length === 0) {
res.send({code: 1, ErrorMsg: '暫無當(dāng)前賬號澳窑,請先注冊斧散!'});
} else {
const user = JSON.parse(JSON.stringify(results[0]));
bcrypt.compare(password, user.password, function(err, result) {
// result == true
if (err) {
console.error(err);
res.send({code: 1, ErrorMsg: 'Internal Server Error'});
} else if(result) {
const Token = createToken(user)
//刪除密碼信息
delete user.password;
user.roles = ['admin'];
res.send({code: 0, data: {
token: Token,
userInfo: user
}})
} else {
res.send({code: 1, ErrorMsg: '密碼錯誤,請重試!'});
}
});
}
})
})