mysql
一、创建MySQL模块
1、介绍
是Node.js下专门用于操作mysql数据库的模块
2、下载安装
npm install mysql
3、连接数据库
mysql.exe -h127.0.0.1 -P3306
-uroot -p
mysql -uroot
mysql -uroot<拖拽SQL脚本文件
//引入MySQL模块
const mysql=require('mysql');
//创建连接对象
const c=mysql.createConnection({
host: '127.0.0.1',
port: '3306',
user: 'root',
password: '',
database: 'tedu'
});
//测试连接
c.connect();
4、reatePool( ) 创建连接池
//引入mysql模块
const mysql=require('mysql');
//创建连接池对象
const pool=mysql.createPool({
host:'127.0.0.1',
port:'3306',
user:'root',
password:'',
database:'tedu',
connectionLimit:15 //连接池的大小,默认也是15
});
5、pool.query()
(SQL命令, 数组, 回调函数 ) 执行SQL命令,数组保存用来过滤的数据,最后再去替换占位符,通过回调函数获取结果
//引入mysql模块
const mysql=require('mysql');
//创建连接池对象
const pool=mysql.createPool({
host:'127.0.0.1',
port:'3306',
user:'root',
password:'',
database:'tedu',
connectionLimit:15 //连接池的大小,默认也是15
});
//比如查到一个数据,浏览器发请求给服务器端,服务器去连接数据库服务器查找,找到了就响应给浏览器
//query是异步的,得通过回调函数获取结果
pool.query('select * from emp',(err,result)=>{
if(err) throw err;
console.log(result);
})
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-MUb5SN15-1635344598544)(C:\Users\23204\AppData\Roaming\Typora\typora-user-images\image-20211002174842723.png)]
6、SQL注入
select * from emp where 1; //1是true,表示显示所有的数据
select * from emp where ename=“tao” or “1”;
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-8yT7fsSf-1635344598547)(C:\Users\23204\AppData\Roaming\Typora\typora-user-images\image-20211002181138451.png)]
占位符(?):先将用户提供的值进行过滤,过滤完再替换位置。
select* from emp where sex=? and salary>? , [0, 8000]
//引入mysql模块
const mysql=require('mysql');
//创建连接池对象
const pool=mysql.createPool({
host:'127.0.0.1',
port:'3306',
user:'root',
password:'',
database:'tedu',
connectionLimit:15 //连接池的大小,默认也是15
});
//比如查到一个数据,浏览器发请求给服务器端,服务器去连接数据库服务器查找,找到了就响应给浏览器
//query是异步的,得通过回调函数获取结果
//假设查找到一个员工的姓名,把员工姓名保存到变量
var user='tao';
//把user变量拼接到sql命令去
//执行SQL命令,查询出该员工的数据
//select*from emp where ename='tao';
//第一种方法:'select*from emp where ename="'+ ['tao'] +'"'
// pool.query('select*from emp where ename="'+ user +'"',(err,result)=>{
// if(err) throw err;
// console.log(result);
// })
//第二种方法:占位符(?):先将用户提供的值进行过滤,过滤完再替换位置。
pool.query('select*from emp where ename=?',[user],(err,result)=>{
if(err) throw err;
console.log(result);
})
/*
//insert into emp values(null,...);
pool.query('insert into emp values(null,?,?,?,?,?)',[user.ename,user.sex,user.birthday,user.salary,user.deptId],(err,result)=>{
if(err) throw err;
console.log(result);
});
*/
二、后端接口
接口:后端提供的动态资源(注册、登录、数据操作…)
RESTful接口:是一种接口风格
1、URL
员工资源
http://127.0.0.1:8080/v1/emps 多个资源
v1:版本号 emps:资源名称(复数形式)
http://127.0.0.1:8080/v1/emps/3 单个资源
3: 编号
用户资源
http://127.0.0.1:8080/v1/users/login 对资源的操作方