当前位置:网站首页>Express framework connects MySQL and ORM framework
Express framework connects MySQL and ORM framework
2022-07-30 17:00:00 【THER1881】
一、Express框架连接MySQL数据
1、安装MySQL模块
npm install mysql

2、创建一个配置文件:用于连接MySQL数据库
创建配置文件Sql.js:
var dbmysql ={
host:'127.0.0.1',
port:3306,
user:'root',
password:'qazzaq123',
database:'mvc'
}
module.exports = dbmysql;
连接数据库crud.js
var express = require('express')
var mysql = require('mysql')
var dbmysql = require('../config/Sql')
var router = express.Router()
//http://localhost:3000/posts/db
router.get('/db',(req, res) => {
//1、连接数据库,获取数据库的连接对象
let conn = mysql.createConnection(dbmysql);
console.log(conn)
//2、d调用数据库连接对象的query方法进行查询
conn.query('select * from edu',function (err,results,fields){
if(err){
throw err
}
console.log(results) //输出查询结果
res.send(results)
})
//3、关闭数据库的连接
conn.end((err)=>{
if(err){
console.log(err)
return
}
})
})
module.exports=router
3、在前端页面中使用表单来收集数据
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
div{
width: 500px;
margin: 50px auto;
}
</style>
<body>
<div>
<form id="reg">
<label for="">
学号:<input type="text" name="s_id">
</label>
<br><br>
<label for="">
姓名:<input type="text" name="s_name">
</label>
<br><br>
<label for="">
年龄:<input type="number" name="s_age">
</label>
<br><br>
<label for="">
性别:<input type="text" name="s_gender">
</label>
<br><br>
<button type="button" id="btn_ok">提交</button>
</form>
<br><br>
<span id="msg"></span>
</div>
</body>
</html>

4、通过jQuery的方法向服务器发起异步请求,将数据提交给服务器
5、服务器接收到前端的请求数据后,将数据写入数据库,同时给前端发送响应信息
5.1、增加数据:
Ajax异步请求代码:
<script>
$(function(){
$('#btn_ok').bind('click',function(){
//向服务器发起ajax请求
$.ajax({
url:'http://localhost:3000/post/add',
type:'post',
datatype:'json',
data:$('#reg').serialize(), //表单序列化
success:function(result){
$('#msg').html(result.info)
},
error:function(err){
console.log(err)
}
})
})
服务器后端代码:
var express = require('express')
var mysql = require('mysql')
var dbmysql = require('../config/Sql')
var router = express.Router()
// http://localhost:3000/posts/adds
router.post('/adds',(req, res) => {
//1.接收客户端的请求数据
let sid = req.body.s_id
let sname = req.body.s_name
let age = req.body.s_age
let gender = req.body.s_gender
//2、将数据封装成对象
let data = {
sid,sname,age,gender}
//3、创建数据库的连接对象
let conn = mysql.createConnection(dbmysql);
//4、将数据插入到数据库中
conn.query('insert into edu set ?',data,function (err,result){
if (err){
console.log(err)
res.send({
code:1001,
info:'数据插入失败'
})
}else{
res.send({
code:1002,
info:'数据插入成功'
})
}
})
//5、关闭数据库连接
conn.end((err)=>{
if(err){
console.log(err)
return
}
})
})
module.exports=router

5.2、查询操作:
(1)、服务器后端代码:
var express = require('express')
var mysql = require('mysql')
var dbmysql = require('../config/Sql')
var router = express.Router()
//http://localhost:3000/posts/db
router.get('/db',(req, res) => {
//1、连接数据库,获取数据库的连接对象
let conn = mysql.createConnection(dbmysql);
console.log(conn)
//2、d调用数据库连接对象的query方法进行查询
conn.query('select * from edu',function (err,results,fields){
if(err){
throw err
}
console.log(results) //输出查询结果
res.send(results)
})
//3、关闭数据库的连接
conn.end((err)=>{
if(err){
console.log(err)
return
}
})
})
module.exports =router;
(2)、使用ApipostTest query query results
5.3、删除操作:
<script src="../js/jquery-3.4.1.js"></script>
<script>
$(function(){
$('#btn_del').bind('click',function(){
$.ajax({
url:'http://localhost:3000/crud/remove',
type:'delete',
dataType:'json',
data:{
s_id:$('#sid').val()},
success:function(result){
$('#msg').html(result.info)
},
error:function(err){
console.log(err)
}
})
})
})
</script>
服务器后端代码:
var express = require('express')
var mysql = require('mysql')
var dbmysql = require('../config/Sql')
var router = express.Router()
//http://localhost:3000/posts/remove
router.delete('/remove',(req, res) => {
// 1. 获取客户端的请求数据
let sid = req.body.s_id
// 2. 获取数据库的连接
let conn = mysql.createConnection(dbmysql);
// 3.执行删除
conn.query('delete from edu where sid=?',sid,function (err,result){
if (err){
console.log(err)
res.send({
code: 1001,
info: '删除失败'
})
}else{
res.send({
code: 1002,
info: '删除成功'
})
}
})
conn.end((err)=>{
console.log(err)
return
})
})
module.exports=router
运行结果:

5.4、修改操作
Ajax异步请求代码:
$('#btn_update').bind('click',function(){
$.ajax(
{
url:'http://localhost:3000/crud/modify',
type:'put',
dataType:'json',
data:$('#reg').serialize(),//表单序列化
success:function(result){
$('#msg').html(result.info)
},
error:function(err){
console.log(err)
}
})
})
var express = require('express')
var mysql = require('mysql')
var dbmysql = require('../config/Sql')
var router = express.Router()
router.put('/modify',(req, res) => {
// 1.就是客户端的请求数据
let sid = req.body.s_id
let sname = req.body.s_name
let age = req.body.s_age
let gender = req.body.s_gender
// 2.创建数据库的连接对象
let conn = mysql.createConnection(dbconfig);
// 3.将数据插入到数据库中
conn.query("update edu set sname=?,age=?,gender=? where sid=?",[sname,age,gender,sid],function (err,result){
if (err){
console.log(err)
res.send({
code:1001,
info:'数据更新失败'
})
}else{
res.send({
code: 1002,
info: '数据更新成功'
})
}
})
//4.关闭数据库连接
conn.end((err)=>{
if (err){
console.log(err)
return
}
})
})
module.exports=router
Data content before modification:
修改后:
二、ORM(Object Relational Mapping,对象关系映射)
1、什么是ORM框架
ORM(Object Relational Mapping,对象关系映射),是一种为了解决面向对象与关系数据库存在的互不匹配的现象的技术,通过描述对象和数据库之间映射的元数据,把程序中的对象自动持久化到关系数据库中.它的作用是在关系型数据库和对象之间作一个映射,这样,我们在具体的操作数据库的时候,就不需要再去和复杂的SQL语句打交道,只要像平时操作对象一样操作它就可以了.
2、对象关系映射:
类 — 表
类的属性 — 表的列
类的对象 — 表的行
在jsOperations on objects in a program,Is the operation of the row of the database table
3、ORM框架:Sequelize
3.1、什么是Squelize
基于promise的关系型数据库ORM框架,这个库完全采用JavaScript开发并且能够用在Node.JS环境中,易于使用,支持多SQL方言(dialect),.它当前支持MySQL、MariaDB、SQLite、PostgreSQL、Sql Server 数据库.
3.2、Sequelize的特点:
强大的模型定义,支持虚拟类型.
支持完善的数据验证,减轻前后端的验证压力.
Sequelize的查询非常全面和灵活
3.3、具体使用
(1)、安装模块
npm install mysql2
npm install sequelize
安装mysql2:
安装sequelize:
(2)、Create a configuration object for database connections:使用sequelize完成相关配置
配置sequelize(dbconfig.js):
//1、导入squelize模块
const Sequelize = require('sequelize')
//2、配置数据库连接对象
const sqllize =new Sequelize('mvc','root','qazzaq123',{
host:'localhost',
post:3306,
dialect:'mysql',
pool:{
//数据库连接池
max:10,
min:3,
idle:10000
}
})
//3、Export the configuration object of the database
module.exports = sqllize
(3)使用sequelize建立模型(类),The model is implemented with datatablesormMapping to create a model(Model):
//1、导入sequelize模块
const Sequelize = require('sequelize')
//2、导入配置文件
const sqllize = require('../seq')
//3、创建数据模型
const Student = sqllize.define('edu',{
Id:{
type:Sequelize.STRING, //数据类型
primaryKey:true, //主键
field:'sid'
},
Name:{
type:Sequelize.STRING,
field:'sname',
allowNull:false //表示该列不能为空(false)
},
age:{
type:Sequelize.INTEGER,
field:'age',
allowNull:false
},
gender:{
type:Sequelize.STRING,
field:'gender',
allowNull:false //表示该列不能为空(false)
}
},{
freezeTableName:true,
timestamps:false
})
module.exports = Student
(4)使用模型进行crud操作(增删改查)
a、查询所有数据:
const express = require('express')
const router = express.Router()
const Student = require('../config/model/stu')
//测试Sequelize模块
// http://localhost:3000/sequelize/seq
router.get('/seq',(req,res) => {
Student.findAll({
raw:true //不显示时间戳
}).then(function (result){
res.send(result)
})
})
module.exports = router
使用Apipost进行测试:

可以看到在ApipostAll data is displayed after testing in (Only a portion of the data is captured here).
b、Query a certain data:
const express = require('express')
const router = express.Router()
const Student = require('../config/model/stu')
// http://localhost:3000/sequelize/one
router.get('/one',(req, res) => {
Student.findOne({
where:{
Id: 's_1002'
}
}).then((data)=>{
res.send(data)
})
})
module.exports = router
查询结果:
三、Sequelize的查询
1、查询部分字段
const express = require('express')
const router = express.Router()
const Student = require('../config/model/stu')
const sequelize = require('sequelize')
const Op = sequelize.Op
//测试Sequelize模块
//http://localhost:3000/sequelize/seq
router.get('/seq',(req,res) => {
Student.findAll({
attributes:['sid','sname'],//查询部分字段
raw:true //不显示时间戳
}).then(function (result){
res.send(result)
})
})
module.exports=router
2、通过sequelize.fn()method to perform aggregate queries
const express = require('express')
const router = express.Router()
const Student = require('../config/model/stu')
const sequelize = require('sequelize')
//测试Sequelize模块
//http://localhost:3000/sequelize/seq
router.get('/seq',(req,res) => {
Student.findAll({
attributes[[sequelize.fn('count',sequelize.col('sid')),'记录总数']],
raw:true //不显示时间戳
}).then(function (result){
res.send(result)
})
})
module.exports=router

3、查询操作符的使用:需要导入Sequelize模块的Op子模块
3.1、模糊查询:
const express = require('express')
const router = express.Router()
const Student = require('../config/model/stu')
const sequelize = require('sequelize')
const Op = sequelize.Op
//测试Sequelize模块
//http://localhost:3000/sequelize/seq
router.get('/seq',(req,res) => {
Student.findAll({
where:{
sname:{
[Op.like]:'li%'}
},
raw:true //不显示时间戳
}).then(function (result){
res.send(result)
})
})
module.exports=router

3.2、in查询:
const express = require('express')
const router = express.Router()
const Student = require('../config/model/etu')
const sequelize = require('sequelize')
const Op = sequelize.Op
//测试Sequelize模块
//http://localhost:3000/sequelize/seq
router.get('/seq',(req,res) => {
Student.findAll({
where:{
age:{
[Op.in]:[15,23]
},
raw:true //不显示时间戳
}).then(function (result){
res.send(result)
})
})
module.exports=router

3.3、查询结果排序:order
const express = require('express')
const router = express.Router()
const Student = require('../config/model/stu')
const sequelize = require('sequelize')
const Op = sequelize.Op
//测试Sequelize模块
//http://localhost:3000/sequelize/seq
router.get('/seq',(req,res) => {
Student.findAll({
where:{
age:{
order:[
['age','desc']
],
raw:true //不显示时间戳
}).then(function (result){
res.send(result)
})
})
module.exports=router
4、and 和 or 查询
and查询:
const express = require('express')
const router = express.Router()
const Student = require('../config/model/stu')
const sequelize = require('sequelize')
const Op = sequelize.Op
//测试Sequelize模块
//http://localhost:3000/sequelize/seq
router.get('/seq',(req,res) => {
Student.findAll({
where:{
[Op.and]:[
{
sname:{
[Op.like]:'li%'
}
},
{
age:{
[Op.eq]:23
}
}
]
},raw:true //不显示时间戳
}).then(function (result){
res.send(result)
})
})
module.exports=router

5、limit 和 offse
const express = require('express')
const router = express.Router()
const Student = require('../config/model/stu')
const sequelize = require('sequelize')
const Op = sequelize.Op
//测试Sequelize模块
//http://localhost:3000/sequelize/seq
router.get('/seq',(req,res) => {
Student.findAll({
limit:5,
offset:4,
raw:true //不显示时间戳
}).then(function (result){
res.send(result)
})
})
module.exports=router

边栏推荐
猜你喜欢

云厂商做生态需要“真连接、真赋能”,用“技术+真金实银”发展伙伴

23. Please talk about the difference between IO synchronization, asynchronous, blocking and non-blocking

OpenCV形状检测

华为云数据治理生产线DataArts,让“数据‘慧’说话”
![[MRCTF2020]Ezaudit](/img/80/d4656abdff20703591ffdc3f5a5ebc.png)
[MRCTF2020]Ezaudit

@Bean注解详解

KDD 2020 | 深入浅出优势特征蒸馏在淘宝推荐中的应用

微信小程序picker滚动选择器使用详解

Large-scale integrated office management system source code (OA+HR+CRM) source code sharing for free

Summary of String Copy, Concatenation, Comparison and Split Functions (1)
随机推荐
onenote use
olap——入门ClickHouse
Gvim order record
Invalid or corrupt jarfile xxx.jar
Invalid or corrupt jarfile xxx.jar
3D激光SLAM:LeGO-LOAM论文解读---激光雷达里程计与建图
全球架构师峰会
数据预处理:离散特征编码方法
数据库课程设计大作业大盘点【建议在校生收藏】
FP6600QSO SOP-8 USB专用充电端口控制器 用于快充电协议和QC2.0/3.0
登录模块调试-软件调试入门
torch.optim.Adam() 函数用法
KDD‘21推荐系统离散特征表征无embedding table Learning to Embed Categorical Features without Embedding Tables for
lotus 1.16.0 最小快照导出 导入
Nervegrowold d2l (7) kaggle housing forecast model, numerical stability and the initialization and activation function
Summary of String Copy, Concatenation, Comparison and Split Functions (1)
lotus 爆块失败
[TypeScript] Introduction, Development Environment Construction, Basic Types
归一化与标准化
23. Please talk about the difference between IO synchronization, asynchronous, blocking and non-blocking