溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Node.js+Express+Mysql如何實現(xiàn)增刪改查

發(fā)布時間:2021-05-21 10:24:51 來源:億速云 閱讀:204 作者:小新 欄目:web開發(fā)

這篇文章主要介紹了Node.js+Express+Mysql如何實現(xiàn)增刪改查,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

安裝

node 直接去官網(wǎng)下載選擇下載即可https://nodejs.org/en/download/current/

cnpm install express //express框架安裝
cnpm install mysql //mysql驅(qū)動安裝
 brew install mysql //數(shù)據(jù)庫的安裝,根據(jù)命令行提示初始化配置
 mysql.server start//啟動mysql服務(wù)
 mysql.server stop//停止mysql服務(wù)
 mysql -u用戶名 -p用戶密碼//登錄mysql

nodejs連接數(shù)據(jù)庫時報錯

Error: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support
authentication protocol requested by server; consider upgrading MySQL client

查到的結(jié)論是: MySQL8.0版本的加密方式和MySQL5.0的不一樣,連接會報錯。

解決方法如下: 通過命令行進(jìn)入解壓的mysql根目錄下。

登陸數(shù)據(jù)庫

mysql -uroot -p

輸入root的密碼

Enter password: ******

更改加密方式

mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'password' PASSWORD EXPIRE NEVER;

更改密碼:該例子中 123456為新密碼

mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '123456';

刷新:

mysql> FLUSH PRIVILEGES;

數(shù)據(jù)庫的連接

var mysql = require('mysql');//引入數(shù)據(jù)庫驅(qū)動模塊
//console.log(mysql)
// 連接數(shù)據(jù)庫的配置
var connection = mysql.createConnection({
 // 主機(jī)名稱,一般是本機(jī)
 host: 'localhost',
 // 數(shù)據(jù)庫的端口號,如果不設(shè)置,默認(rèn)是3306
 port: '3306',
 // 創(chuàng)建數(shù)據(jù)庫時設(shè)置用戶名
 user: 'root',
 // 創(chuàng)建數(shù)據(jù)庫時設(shè)置的密碼
 password: '*******',
 // 創(chuàng)建的數(shù)據(jù)庫
 database: 'express'
});
// 與數(shù)據(jù)庫建立連接
connection.connect();
// 查詢數(shù)據(jù)庫
connection.query('select * from userinfo', function (error, results, fields) {
 if (error) throw error;
 console.log(results);
});

// 關(guān)閉連接
connection.end();

新建一張表格在數(shù)據(jù)庫中為:

Node.js+Express+Mysql如何實現(xiàn)增刪改查

express服務(wù)端

Express 是一個基于 Node.js 平臺的極簡、靈活的 web 應(yīng)用開發(fā)框架,這里沒有搭建express框架的項目,只是簡單搭建一個服務(wù)端,實現(xiàn)和數(shù)據(jù)庫的增刪改查。

var express = require("express");
var app = express();
var query = require('./db')
//var router =require('router')
var mysql = require('mysql');
var querystring = require("querystring");
//console.log(mysql)
// 連接數(shù)據(jù)庫的配置
var connection = mysql.createConnection({
 // 主機(jī)名稱,一般是本機(jī)
 host: 'localhost',
 // 數(shù)據(jù)庫的端口號,如果不設(shè)置,默認(rèn)是3306
 port: '3306',
 // 創(chuàng)建數(shù)據(jù)庫時設(shè)置用戶名
 user: 'root',
 // 創(chuàng)建數(shù)據(jù)庫時設(shè)置的密碼
 password: '1234567',
 // 創(chuàng)建的數(shù)據(jù)庫
 database: 'express'
});
// 與數(shù)據(jù)庫建立連接
connection.connect();
//根據(jù)參數(shù),查詢數(shù)據(jù)
app.get('/index', function (req, res) {
 // 處理 get 請求,獲取 get 請求參數(shù)
 //處理 /:xxx 形式的 get 或 post 請求,獲取請求參數(shù) 這里沒有使用到
 var params = req.query
 //查詢語句
 var sql = 'select * from userinfo where name= ? and age=?'
 var where_value = [params.name, params.age];
 // console.log(sql)
 connection.query(sql, where_value, function (err, result) {
 if (err) {
  console.log('[SELECT ERROR]:', err.message);
 }
 res.send(result) //數(shù)據(jù)庫查詢結(jié)果返回到result中,把查詢數(shù)據(jù)發(fā)送到客戶端
 });

})
//增加數(shù)據(jù)
app.post('/add', function (req, res) {
 //獲取及處理增加的數(shù)據(jù)
 var post = '';
 req.on('data', function (chunk) {
 post += chunk;
 console.log(post)
 });
 req.on('end', function () {
 //查詢參數(shù)解析
 post = querystring.parse(post);
 var sql = 'insert into userinfo set id=? , name=? , age=?, address=?'
 var add_value = [post.id, post.name, post.age, post.address]
 connection.query(sql, add_value, function (err, result) {
  if (err) {
  console.log('新增數(shù)據(jù)失敗');
  }
  res.send('增加數(shù)據(jù)成功') // 響應(yīng)內(nèi)容 增加數(shù)據(jù)成功
 });
 });
})
//修改數(shù)據(jù)
app.put('/update', function (req, res) {
 //處理請求修改的數(shù)據(jù)和條件
 var update = '';
 req.on('data', function (chunk) {
 update += chunk;
 console.log(update)
 });
 req.on('end', function () {
 //查詢參數(shù)解析
 update = querystring.parse(update);
 var sql = 'update userinfo set name=? , age=?, address=? where id=?'
 var update_value = [update.name, update.age, update.address,update.id]
 connection.query(sql, update_value, function (err, result) {
  if (err) {
  console.log('修改數(shù)據(jù)失敗', err.message);
  }
  res.send('修改數(shù)據(jù)成功') // 響應(yīng)內(nèi)容 修改數(shù)據(jù)成功
 });
 });
})
//刪除數(shù)據(jù)
app.delete('/delete', function (req, res) {
 var params = req.query
 var sql = 'delete from userinfo where name= ?'
 var where_value = [params.name];
 // console.log(sql)
 connection.query(sql, where_value, function (err, result) {
 if (err) {
  console.log('刪除失敗', err.message);
 }
 res.send('刪除成功')
 });
})
//關(guān)閉連接 
//connection.end();
//監(jiān)聽8080端口
var server = app.listen(8080, function () {
 console.log('server running at 3000 port')
})

http客戶端

這里把node http模塊來搭建客戶端,發(fā)起請求。

get請求

const http = require("http");
// 發(fā)送請求的配置
let config = {
 host: "localhost",
 port: 8080,
 //get請求參數(shù)
 path:'/index?name=bill&age=21',
 method: "GET",
 headers: {
 a: 1
 }
};
// 創(chuàng)建客戶端
let client = http.request(config, function(res) {
 // 接收服務(wù)端返回的數(shù)據(jù)
 let repData='';
 res.on("data", function(data) {
 repData=data.toString()
 console.log(repData)
 });
 res.on("end", function() {
 // console.log(Buffer.concat(arr).toString());
 });
});
// 發(fā)送請求
client.end();

客戶端發(fā)起參數(shù)name=bill&age=21的查詢請求,服務(wù)端根據(jù)條件操作數(shù)據(jù)庫,響應(yīng)數(shù)據(jù)為:

Node.js+Express+Mysql如何實現(xiàn)增刪改查

post請求

var http = require('http');
var querystring = require("querystring");
//查詢參數(shù)拼接
//增加的數(shù)據(jù)
var contents = querystring.stringify({
 id:5,
 age:'23',
 name: "艾利斯提",
 address: "dongbei",
});
var options = {
 host: "localhost",
 port: 8080,
 path:"/add",
 method: "POST",
 headers: {
 "Content-Type": "application/x-www-form-urlencoded",
 "Content-Length": contents.length
 }
};
var req = http.request(options, function (res) {
 res.setEncoding("utf8");
 res.on("data", function (data) {
 console.log(data);
 })
})
//發(fā)送數(shù)據(jù)
req.write(contents);
req.end(); //結(jié)束請求,否則服務(wù)器將不會收到信息

post請求發(fā)送增加數(shù)據(jù),服務(wù)端根據(jù)請求,向數(shù)據(jù)庫追加一條數(shù)據(jù),響應(yīng)客戶端:增加數(shù)據(jù)成功。增加后的數(shù)據(jù)表:

Node.js+Express+Mysql如何實現(xiàn)增刪改查

put請求

const http = require("http");
var querystring = require("querystring");
//查詢參數(shù)拼接
// 發(fā)送請求的配置
var contents = querystring.stringify({
 id:1,
 age:'25',
 name: "Sarah",
 address: "qingdao",
});
let config = {
 host: "localhost",
 port: 8080,
 path:'/update',
 method: "PUT",
 headers: {
 a: 1
 }
};
// 創(chuàng)建客戶端
let client = http.request(config, function(res) {
 // 接收服務(wù)端返回的數(shù)據(jù)
 let repData='';
 res.on("data", function(data) {
 repData=data.toString()
 console.log(repData)
 });
 
});
 client.write(contents);
// 發(fā)送請求
client.end();

這里請求和post方法類似,服務(wù)端根據(jù)sql語句('update userinfo set name=? , age=?, address=? where id=?')修改數(shù)據(jù)庫的內(nèi)容,響應(yīng)客戶端:修改數(shù)據(jù)成功。修改后的數(shù)據(jù)表:

Node.js+Express+Mysql如何實現(xiàn)增刪改查

delete請求

const http = require("http");
// 發(fā)送請求的配置
let config = {
 host: "localhost",
 port: 8080,
 //刪除數(shù)據(jù)的參數(shù)
 path:'/delete?name=bill',
 method: "DELETE",
 headers: {
 a: 1
 }
};
// 創(chuàng)建客戶端
let client = http.request(config, function(res) {
 // 接收服務(wù)端返回的數(shù)據(jù)
 let repData='';
 res.on("data", function(data) {
 repData=data.toString()
 console.log(repData)
 });
 res.on("end", function() {
 // console.log(Buffer.concat(arr).toString());
 });
});
// 發(fā)送請求
client.end();

客戶端發(fā)送刪除數(shù)據(jù)的參數(shù),客戶端拿到參數(shù),根據(jù)條件,操作數(shù)據(jù)庫刪除相應(yīng)數(shù)據(jù),響應(yīng)客戶端:刪除成功。刪除后的數(shù)據(jù)表:

Node.js+Express+Mysql如何實現(xiàn)增刪改查

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“Node.js+Express+Mysql如何實現(xiàn)增刪改查”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識等著你來學(xué)習(xí)!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI