当前位置:网站首页>[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 :
边栏推荐
- Sign the college entrance examination
- Webrtc realizes simple audio and video call function
- No, just stick to it for 64 days. Find the insertion location
- Two forms of softmax cross entropy + numpy implementation
- Don't stick to it for 68 days. Baboons eat bananas
- 11. Backup switch
- 不会就坚持68天吧 狒狒吃香蕉
- Exception resolution: error of not finding edu.stanford.nlp.semgraph.semgrex.semgrexpattern in cococaption package
- [k210 stepping pit] pytorch model is converted to kmodel and used on dock. (ultimately not achieved)
- Leftmost prefix principle of index
猜你喜欢

Visio draw grid

不会就坚持62天吧 单词之和

Hengxing Ketong invites you to the 24th China expressway informatization conference and technical product exhibition in Hunan

Deploy Jenkins using containers

恒星科通邀您“湘”约第24届中国高速公路信息化大会暨技术产品展示会

visio画网格

6. Pytest generates an allure Report

Post export data, return

MySQL - deep parsing of MySQL index data structure
![[hands on deep learning] environment configuration (detailed records, starting from the installation of VMware virtual machine)](/img/fe/8c707c30c734de7bb76ea68134842c.png)
[hands on deep learning] environment configuration (detailed records, starting from the installation of VMware virtual machine)
随机推荐
Can you really write restful API?
C language: talking about various complex statements
Two forms of softmax cross entropy + numpy implementation
Not 67 days, square root
Niuke IOI weekly 27 popularity group
Integration of Nan causes in pytorch training model
C language force buckle question 61 of the rotating list. Double ended queue and construction of circular linked list
Methods of using multiple deformations on an element
Unity基础(3)—— unity中的各种坐标系
[hands on deep learning] environment configuration (detailed records, starting from the installation of VMware virtual machine)
Differences and principles of bio, NiO and AIO
不会就坚持68天吧 狒狒吃香蕉
How to query the submission number of a version
不会就坚持58天吧 实现前缀树
Mpc5744p introduction and opensda firmware update
Shell string segmentation
No, just stick to it for 64 days. Find the insertion location
C language: summary of consortium knowledge points
Basic operation of queue
Pytorch GPU and CPU models load each other