当前位置:网站首页>[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 :
边栏推荐
猜你喜欢
随机推荐
Coding questions encountered in the interview
How to query the submission number of a version
C语言:浅谈各种复杂的声明
On quotation
C language: talking about various complex statements
The third ACM program design competition of Wuhan University of Engineering
6. Pytest generates an allure Report
Leetcode 686. KMP method of repeatedly superimposing strings (implemented in C language)
Beginner: array & String
Why are there so many unknowns when opengauss starts?
Why is it necessary to scale the attention before softmax (why divide by the square root of d_k)
Exception resolution: error of not finding edu.stanford.nlp.semgraph.semgrex.semgrexpattern in cococaption package
不会就坚持66天吧 权重生成随机数
信号处理中的反傅里叶变换(IFFT)原理
Compilation and linking
14.haproxy+keepalived负载均衡和高可用
Multi card training in pytorch
异常处理:pyemd或PyEMD找不到
你真的会写Restful API吗?
SQL time fuzzy query datediff() function









