假设你已经安装好本地mysql 和管理工具navicat-for-mysql;
1、安装 node.js的mysql模块
npm install --save mysql
2、新建目录./async-db/query.js;
/**
* Created by Administrator on 2018/11/16 0016.
* 连接池管理会话
* 封装一个query函数,可以执行SQL语句
*/
const mysql = require('mysql');
const config=require('../config');//mysql的账号密码等数据;
console.log(config.mysql_config.database,"config.mysql_config")
// 创建数据池
const pool = mysql.createPool(config.mysql_config)
let query = function( sql, values ) {
return new Promise(( resolve, reject ) => {
// 在数据池中进行会话操作
pool.getConnection((err, connection)=> {
// 如果有错误就抛出
if (err) {
reject( err )
} else {
connection.query(sql, values, ( err, rows) => {
if ( err ) {
reject( err )
} else {
resolve( rows )
}
// 结束会话
connection.release()
})
}
})
})
}
3.在根目录下的config.js 中
const config = {
port: 3000,
mysql_config: {
host: 'localhost', // 数据库地址
port:'3306',
user: 'root', // 数据库用户
password: '123456', // 数据库密码
database: 'koa2-test' // 选中数据库名称
}
};
module.exports = config;
4 新建目录./async-db/sql.js; 存放SQL语句;我这里只举个例子;其他语句可视情况自行添加;
const {query}=require('./query')
//数据库设计
//用户表(users):id、name、pass
//let users = `create table if not exists users(
// id INT NOT NULL AUTO_INCREMENT,
// name VARCHAR(100) NOT NULL,
// pass VARCHAR(40) NOT NULL,
// PRIMARY KEY ( id )
//
//);`;
////文章表(posts):id、name、title、content、uic、moment、comments、pv
//
//let posts = `create table if not exists posts(
// id INT NOT NULL AUTO_INCREMENT,
// name VARCHAR(100) NOT NULL,
// title VARCHAR(40) NOT NULL,
// content VARCHAR(40) NOT NULL,
// uid VARCHAR(40) NOT NULL,
// moment VARCHAR(40) NOT NULL,
// comments VARCHAR(40) NOT NULL DEFAULT '0',
// pv VARCHAR(40) NOT NULL DEFAULT '0',
// PRIMARY KEY ( id )
//);`;
////评论表(comment):id、name、content、postid
//let comment = `create table if not exists comment(
// id INT NOT NULL AUTO_INCREMENT,
// name VARCHAR(100) NOT NULL,
// content VARCHAR(40) NOT NULL,
// postid VARCHAR(40) NOT NULL,
// PRIMARY KEY ( id )
//);`;
//
//let createTable = function(sql) {
// return query(sql, []);
//};
//createTable(users);
//createTable(posts);
//createTable(comment);
// 查找用户
let findUserData = function( name ) {
let _sql = `select * from users where name="${name}";`
return query( _sql)
}
//
module.exports = {findUserData }
在数据库中创建一个表。和表内容;
现在开始查询用户;
在myrotuer/login.js中添加路由;
const sql=require('../async-db/sql.js')
router.get('/api/AlarmHandle/GetLogin', async (ctx, next) => {
let name=ctx.query.account;
let pass=ctx.query.password;
await sql.findUserData(name)
.then(res=> {
if(res.length!=0){
if (name === res[0]['name'] &&pass === res[0]['pass']) {
console.log('登录成功')
console.log(ctx.response.status)
}else{
}
}else{
console.log('登录失败')
}
next();
})
})
下一篇我打算写token校验。前后端分离;