当前位置:网站首页>[express connection to MySQL database]
[express connection to MySQL database]
2022-07-29 04:27:00 【꒰ঌsnail໒꒱】
Catalog
1、 install MySQL modular
npm install mysql
2、 Create a profile
Create a profile : Used to connect to MySQL database
3、 increase , Delete , Change , Check operation
The general flow is as follows :
(1) Use forms in front pages to collect data
(2) adopt jQuery Method to send an asynchronous request to the server , Submit the data to the server
(3) After the server receives the request data from the front end , Write data to the database , At the same time, send response information to the front end
dbconfig.js The configuration file code is as follows :
var dbconfig = {
host:'localhost',
port:3306,
user:'root',
password:'123456',
database:'xy' // Name of the connected database
}
module.exports =dbconfig;
app.js Back end code :
var crudRouter =require('./routes/crud')
app.use('/crud',crudRouter);
(1) Query operation
crud.js The database routing code is as follows :
var express =require('express')
var mysql = require('mysql')// Guide module
var dbconfig = require('../config/dbconfig')// Import custom module
var router = express.Router()
//http://localhost:3000/crud/findAll
router.get('/findAll',(req, res) => {
//1、 Connect to database , Get the connection object of the database
let conn = mysql.createConnection(dbconfig);
console.log(conn)
//2、 Call the... Of the database connection object query Method to execute the query
conn.query('select * from stu',function(err,results,fields){
if(err){
throw err
}
console.log(results)// Output query results
res.send(results)
})
//3、 Close the connection to the database
conn.end((err)=>{
if(err){
console.log(err)
return
}
})
})
module.exports =router;
The operation results are as follows :
stay postman The software test is as follows :
(2) Increase the operating
️ The front page code is as follows ( Because of the need to use JQuery, So import JQuery library ):
<!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>
<body>
<div>
<form id="reg">
<label>
Student number :<input type="text" name="s_id">
</label>
<br><br>
<label>
full name :<input type="text" name="s_name">
</label>
<br><br>
<label>
Age :<input type="number" name="s_age">
</label>
<br><br>
<label>
Gender :<input type="text" name="s_gender">
</label>
<br><br>
<button type="button" id="btn_ok"> Submit </button>
<button type="button" id="btn_update"> modify </button>
</form>
<br><br>
<span id="msg"></span>
<br><br>
<label>
Deleted student number :<input type="text" id="sid">
<button type="button" id="btn_del"> Delete </button>
</label>
</div>
</body>
</html>
Ajax Asynchronous request code :
<script src="../js/jquery-3.4.1.js"></script>
<script>
$(function(){
$('#btn_ok').bind('click',function(){
$.ajax(
{
url:'http://localhost:3000/crud/add',
type:'post',
dataType:'json',
data:$('#reg').serialize(),// Form serialization
success:function(result){
//result, It's a json object
$('#msg').html(result.info)
},
error:function(err){
console.log(err)
}
})
})
})
</script>
Server back end code crud.js:
var express =require('express')
var mysql = require('mysql')// Guide module
var dbconfig = require('../config/dbconfig')// Import custom module
var router = express.Router()
//http://localhost:3000/crud/add
router.post('/add',(req, res) => {
//1、 It is the request data of the client
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、 Encapsulate data as objects
let data ={
sid,sname,age,gender}
//3、 Create a database connection object
let conn = mysql.createConnection(dbconfig);
//4、 Insert data into the database
conn.query('insert into stu set ?',data,function(err,result){
if(err){
res.send({
code:1001,
info:' Data insertion failed '
})
}else{
res.send({
code:1002,
info:' Data insertion successful '
})
}
})
//5、 Close database connection
conn.end((err)=>{
if(err){
console.log(err)
return
}
})
})
module.exports =router;
The operation results are as follows :
stay postman The software test is as follows :

(3) Delete operation
Ajax Asynchronous request code :
<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>
Server back end code crud.js:( The rest is the same as above , This is the key code )
//http://localhost:3000/crud/remove
router.delete('/remove',(req, res) => {
//1、 Get the request data of the client
let sid = req.body.s_id
//2、 Get the connection to the database
let conn = mysql.createConnection(dbconfig);
//3、 Execution deletion
conn.query('delete from stu where sid=?',sid,function(err,result){
if(err){
console.log(err)
res.send({
code:1001,
info:' Delete failed '
})
}else{
res.send({
code:1002,
info:' Data deletion successful '
})
}
})
conn.end((err)=>{
if(err) {
console.log(err)
return
}
})
})
The operation results are as follows :
(4) Modify the operating
Ajax Asynchronous request code :
$('#btn_update').bind('click',function(){
$.ajax(
{
url:'http://localhost:3000/crud/modify',
type:'put',
dataType:'json',
data:$('#reg').serialize(),// Form serialization
success:function(result){
$('#msg').html(result.info)
},
error:function(err){
console.log(err)
}
})
})
Server back end code crud.js:( The rest is the same as above , This is the key code )
//http://localhost:3000/crud/modify
router.put('/modify',(req, res) => {
//1、 It is the request data of the client
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、 Create a database connection object
let conn = mysql.createConnection(dbconfig);
//3、 Insert data into the database
conn.query('update stu set sname=?,age=?,gender=? where sid=?',[sname,age,gender,sid],function(err,result){
if(err){
console.log(err)
res.send({
code:1001,
info:' Data update failed '
})
}else{
res.send({
code:1002,
info:' Data updated successfully '
})
}
})
//5、 Close database connection
conn.end((err)=>{
if(err){
console.log(err)
return
}
})
})
database xy Of stu Part of the table is as follows :
We need to modify S_1001 liuYi 35 male This message :
See the table , Data modified successfully :
边栏推荐
猜你喜欢

Not for 63 days. The biggest XOR

使用容器部署Jenkins

MySQL gets the maximum value record by field grouping

不会就坚持66天吧 权重生成随机数

MySQL - deep parsing of MySQL index data structure

6. Pytest generates an allure Report

Deep learning training strategy -- warming up the learning rate

Sequence list and linked list

C language force buckle question 61 of the rotating list. Double ended queue and construction of circular linked list

No, just stick to it for 59 days
随机推荐
VScode 一键编译和调试
Whole house WiFi solution: mesh router networking and ac+ap
读懂 互联网巨头 【中台之战】 以及 中台 发展思维
WebRTC实现简单音视频通话功能
No, just stick to it for 59 days
不会就坚持67天吧 平方根
Model tuning, training model trick
Openfeign asynchronous call problem
C language: structure simple syntax summary
不会就坚持60天吧 神奇的字典
不会就坚持65天吧 只出现一次的数字
Don't stick to it for 68 days. Baboons eat bananas
Jenkins 参数化构建中 各参数介绍与示例
10. Fallback message
Target detection learning process
Methods of using multiple deformations on an element
Locally call tensorboard and Jupiter notebook on the server (using mobaxterm)
Coding questions encountered in the interview
你真的会写Restful API吗?
redux快速上手