導語:以前作過一個小項目,其中用到了node和mysql,如今就結合這二者作一個使用操做總結。CURD是數據庫技術中的縮寫詞,表明建立(Create)、更新(Update)、讀取(Retrieve)和刪除(Delete)操做,用於處理數據等操做。
建議閱讀本博客另外一篇文章《win10手動配置php開發環境教程》php
能夠使用這幾個集成包:html
PHPStudy
LNMP
XAMPP
wampserver
appserv前端
在nodejs官網上面下載而後安裝,一步一步的安裝好了如下,查詢下那個版本。node
本小節經過一個商品的增刪改查來展現如何使用node來鏈接mysql進行各類操做。mysql
$ mkdir demo $ cd demo $ npm init $ npm install express --save $ npm install -g express-generator $ npm install pm2 -g $ npm install supervisor
編寫啓動腳本sql
// index.js const express = require('express'); const app = express(); const port = 3000; const db = require('./mysql'); app.get('/', (req, res) => { res.send('Hello,demo!'); }) app.listen(port, () => { console.log('Server is running on port ', port + '!'); })
在package.json
加入如下命令數據庫
"dev": "node index.js"
express
// package.json { "name": "demo", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "dev": "node index.js" }, "author": "", "license": "ISC", "dependencies": { "express": "^4.17.1", "mysql": "^2.18.1", "supervisor": "^0.12.0" } }
啓動腳本apache
$ npm run start # 或者 $ supervisor index.js
創建一個名叫demo
的數據庫,而後建一個名稱爲goods
的數據表,接着進行以下結構的配置。npm
如下是具體的命令行操做方法。
$ mysql -h 127.0.0.1 -P 3306 -u demo -p # 輸入密碼後回車確認 Enter password:
鏈接成功後以下所示:
Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 455 Server version: 5.7.26 MySQL Community Server (GPL) Copyright (c) 2000, 2021, Oracle and/or its affiliates. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql>
-- 創建demo用戶 mysql> CREATE USER 'demo'@'127.0.0.1' IDENTIFIED BY 'demo123456.'; -- 創建demo數據庫 mysql> CREATE DATABASE demo; -- 賦予用戶demo操做數據庫demo的權限 mysql> GRANT ALL PRIVILEGES ON demo.* TO 'demo'@'127.0.0.1'; FLUSH PRIVILEGES; -- 建立數據表 mysql> CREATE TABLE `goods` ( `id` int(11) NOT NULL COMMENT 'id', `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT '名稱', `number` int(11) NOT NULL COMMENT '數量', `price` int(11) NOT NULL COMMENT '價格', `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '建立時間', `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新時間' ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='商品表';
終於到了最關鍵的一步,首先安裝mysql依賴包。回到demo
目錄下面,而後打開命令行。
$ npm install mysql
// mysql.js const mysql = require('mysql'); const connection = mysql.createConnection({ host: '127.0.0.1', user: 'demo', password: 'demo123456.', database: 'demo' }); connection.connect(function (err) { if (err) { console.error(`error connecting: ${err.stack}`); return; } console.log(`Mysql is connected! 鏈接id: ${connection.threadId}`); }); module.exports = db;
引入index.js
文件中
// index.js const db = require('./mysql');
運行成功後的截圖:
如下操做均在index.js
中操做。
查詢須要用到的語句SELECT <字段> FROM <表名> <查詢條件>
;
例如:
mysql> SELECT * FROM `goods`;
*
表示所有的字段,若是你只想要查詢id和名稱,只須要寫入SELECT id,name FROM "goods"
便可。
// 查詢商品信息 app.get('/goods', (req, res) => { let result = {}; db.query('SELECT * FROM `goods`', function (error, results, fields) { if (error) { result = { code: 101, msg: 'get_fail', data: { info: "查詢失敗!" } } }; result = { code: 200, msg: 'get_succ', data: { info: "查詢成功!", list: results } } res.json(result); }); })
在地址欄輸入http://localhost:3000/goods
,即可以看到查詢的信息。
剛剛查詢了一下,發現裏面的商品空空如也,如今來添加幾條商品信息。
建立須要用到的語句格式大體爲INSERT INTO <表名>(<字段1,字段2,...>) VALUES (值1,)
;
例如:
mysql> INSERT INTO `goods`(`name`, `number`, `price`) VALUES ('香蕉', 8, 10);
注意:添加商品是post
請求,因此須要提早下載一個api接口軟件,有利於測試,比較有名的是postman
。請自行下載安裝。
接着開始進行商品的程序編寫,因爲mysql建議表,字段加反斜線,故本次mysql語句不使用模板字符串,而是使用字符串拼接方法。
安裝body-parser
,這個是解析前端post請求的body內容。
$ npm install body-parser
引入index.js文件。
// index.js // 添加商品 // 引入body-parser const bodyParser = require('body-parser'); app.use(bodyParser.urlencoded({ extended: false })) app.use(bodyParser.json()); app.post('/goods', (req, res) => { let result = {}; let params = req.body; let names = '',values = ''; for (const key in params) { names += '`'+ key + '`,'; if (key == 'name') { values += `"${params[key]}",`; } else { values += `${params[key]},`; } } names = names.slice(0, names.length-1); values = values.slice(0, values.length-1); db.query('SELECT id FROM `goods` WHERE name= "' + params.name + '"', function (error, results, fields) { if (error) { result = { code: 101, msg: 'get_fail', data: { info: "查詢失敗!" } } }; if (results && results.length) { result = { code: 200, msg: 'get_succ', data: { info: "商品已存在!" } } return res.json(result); } db.query('INSERT INTO `goods`(' + names + ') VALUES (' + values + ')', function (error, results, fields) { if (error) { result = { code: 101, msg: 'save_fail', data: { info: "添加失敗!" } } }; result = { code: 200, msg: 'save_succ', data: { info: "添加成功!", des: { id: results[0].insertId } } } return res.json(result); }); }); })
打開postman
,輸入如下內容,而後點擊send
按鈕,發送post請求。
如下是結果截圖。
添加失敗
添加成功
再次查詢商品信息,出現了剛剛添加的內容。
有時候,添加的商品信息會有波動,那麼如今就修改如下實時變更的商品信息屬性。
修改須要用到的語句格式大體爲UPDATE <表名> SET 字段1=值1, 字段2=值2 <條件>
;
例如:
mysql> UPDATE `goods` SET `number` = 15, `price` = 12 WHERE `id` = 1;
下面就修改一下那個蘋果的數量爲15,價格爲9.9。
// 修改商品信息 app.put('/goods', (req, res) => { let result = {}; let params = req.body; if (!params.id) { return res.json({ code: 101, msg: 'get_fail', data: { info: "id不能爲空!" } }) } db.query('SELECT id FROM `goods` WHERE `id` = ' + params.id, function (error, results, fields) { if (error) { result = { code: 101, msg: 'get_fail', data: { info: "查詢失敗!" } } }; if (results && results.length == 0) { result = { code: 200, msg: 'get_succ', data: { info: "商品不存在!" } } return res.json(result); } db.query('UPDATE `goods` SET `number` = ' + params.number + ', `price` = ' + params.price + ' WHERE `id` = ' + params.id, function (error, results, fields) { if (error) { result = { code: 101, msg: 'save_fail', data: { info: "修改失敗!" } } }; result = { code: 200, msg: 'save_succ', data: { info: "修改爲功!" } } return res.json(result); }); }); })
若是商品賣完了,或者不賣了,能夠下架商品,那這裏直接刪除這個商品的信息。
刪除須要用到的語句格式大體爲DELETE FROM <表名> <條件>
;
例如:
mysql> DELETE FROM `goods` WHERE `id` = 1;
下面就刪除一下那個蘋果商品。
// 刪除商品 app.delete('/goods', (req, res) => { let result = {}; let params = req.body; if (!params.id) { return res.json({ code: 101, msg: 'get_fail', data: { info: "id不能爲空!" } }) } db.query('SELECT id FROM `goods` WHERE `id` = ' + params.id, function (error, results, fields) { if (error) { result = { code: 101, msg: 'get_fail', data: { info: "查詢失敗!" } } }; if (results && results.length == 0) { result = { code: 200, msg: 'get_succ', data: { info: "商品不存在!" } } return res.json(result); } db.query('DELETE FROM `goods` WHERE `id` = ' + params.id, function (error, results, fields) { if (error) { result = { code: 101, msg: 'get_fail', data: { info: "刪除失敗!" } } }; result = { code: 200, msg: 'get_succ', data: { info: "刪除成功!" } } return res.json(result); }); }); })
以上就是比較簡單的一個商品的CURD,所列舉的例子都是比較基礎的案例。
通過剛纔的實戰,相信你對curd已經很熟悉了,下面就簡單封裝一個查詢的方法。
// simple.js const simple = (sql, params = null) => { var connection = mysql.createConnection(dbConfig); return new Promise(function (resolve, reject) { connection.connect(); console.log('Database is connected!'); connection.query(sql, params, (err, result) => { if (err) { reject({ code: 102, msg: 'get_fail', data: { info: '查詢失敗!', detail: { errno: err.errno, sqlMessage: err.sqlMessage, sql: err.sql } } }); } else { resolve({ code: 200, msg: 'get_succ', data: { info: '查詢成功!', data: result } }); } }) connection.end(); console.log('Database is disconnected!'); }) }
使用方法:
app.get('/goods/test', async (req, res) => { let data = await simple('SELECT * FROM `goods`'); return res.json(data); });
這裏推薦一個依賴包,這個能夠生成mysql語句。
$ npm install xqsql
具體使用方法,點擊地址有文檔介紹。
這樣就比較方便點,也看着直觀。
好了,今天的總結就到這裏,有什麼疑問,請郵箱聯繫我。