当前位置:网站首页>02. Develop data storage of blog project
02. Develop data storage of blog project
2022-07-06 05:18:00 【John is orange】
Develop data storage for blog projects
Premise : install MySQL, And use graphical interface to facilitate operation (DBeaver、MySQL Workbench etc. )
1. Database operation ( Create, add, delete, modify, and query )
1.1 Creating databases and tables
It can be used SQL Statement writing , But it is simpler and less error prone to operate with a graphical interface .
Right click to create a database , The name is myblog.
Right click myblog, Create two tables :
Blog
user
The password needs to be encrypted
id It's the only sign , It's the primary key , And set it to automatically increase , After inserting data later , You don't need to add it yourself id.
1.2 Additions and deletions
Using a database myblog
use myblog;
see myblog All tables in
show tables;
Add data
INSERT INTO users (username, `password`, realname) VALUES ('admin', '123456', ' Administrators ');
Query data
Inquire about users All columns in :
SELECT * FROM users;
Find data for a specific column , It can optimize query performance :
SELECT id, username FROM users;
Query with query criteria , For example, the query user name is zhangsan Information about :
SELECT * FROM users WHERE username = 'zhangsan';
and and or collocation , It has the same meaning as in programming
SELECT * FROM users WHERE username = 'zhangsan' AND password='123456';
SELECT * FROM users WHERE username = 'zhangsan' OR password='123456'
Fuzzy query , Such as query username Internal band zhang The data of
SELECT * FROM users WHERE username LIKE '%zhang%';
Sorting results ( Default positive order ):
SELECT * FROM users WHERE password LIKE '%1%' ORDER BY id;
If you want to see the result in reverse order :
SELECT * FROM users WHERE password LIKE '%1%' ORDER BY id DESC;
Update data
Be careful , When updating, you should mark the update conditions , Otherwise, all rows will be updated !
UPDATE users SET realname = ' Li Si 2' WHERE username = 'lisi';
Delete data
alike , When deleting data, you should also mark the deletion conditions !
DELETE FROM users WHERE username = 'lisi';
Generally, delete lines are not deleted in this way , But soft delete —— Update fields . There is a field in the table, such as state , The default value is 1. To mark whether it is deleted , If deleted, mark as 0, Otherwise 1. In this way, data recovery can be done well , Instead of permanently deleting .
UPDATE users SET state = 0 WHERE username = 'lisi';
2. nodejs operation MySQL
The data used before are all analog data , You can't use simulated data later , Rather let API To manipulate the database .
install MySQL Third party Library
yarn add mysql
Basic usage
const mysql = require("mysql");
// Create connection objects
const con = mysql.createConnection({
host: "localhost",
user: "root",
password: "123456",
port: "3306",
database: "myblog",
});
// Start connecting
con.connect();
// perform SQL sentence
const sql = "SELECT * FROM users;";
con.query(sql, (err, result) => {
if (err) {
console.log(err);
return;
}
console.log(result);
});
// Close the connection
con.end();
After inputting the necessary information, connect to the resume database , And then execute SQL sentence , And execute successful or failed callbacks .
The result of the above code output :
[
RowDataPacket {
id: 1,
username: 'admin',
password: '123456',
realname: ' Administrators '
},
RowDataPacket {
id: 2,
username: 'zhangsan',
password: '123456',
realname: ' Zhang San '
},
RowDataPacket {
id: 4,
username: 'lisi',
password: '123456',
realname: ' Li Si '
}
]
If sql The statement is as follows :
const sql = "UPDATE users SET realname = ' Li Si 2' WHERE username = 'lisi';";
The returned result is as follows :
OkPacket {
fieldCount: 0,
affectedRows: 1,
insertId: 0,
serverStatus: 34,
warningCount: 0,
message: '(Rows matched: 1 Changed: 1 Warnings: 0',
protocol41: true,
changedRows: 1
}
The returned data has a lot of information . Including the corresponding id, The number of lines affected .
3. nodejs Connect MySQL Tool implementation
above nodejs The writing method of connecting and operating the database is quite laborious , The real core code is SQL Operation code , So we need to optimize .
- Add a profile , Put the configuration required for connection inside :
// conf/db.js
// Get environment parameters
const env = process.env.NODE_ENV;
let MYSQL_CONF = {
};
// The address of the database in the development environment
if (env === "dev") {
MYSQL_CONF = {
host: "localhost",
user: "root",
password: "123456",
port: "3306",
database: "myblog",
};
}
// The address of the database in the production environment
if (env === "production") {
MYSQL_CONF = {
host: "localhost",
user: "root",
password: "123456",
port: "3306",
database: "myblog",
};
}
module.exports = {
MYSQL_CONF,
};
Create unified execution sql Functions and related tools
sql The execution of is asynchronous , So with promise The package is the best .
const mysql = require("mysql"); const { MYSQL_CONF } = require("../conf/db"); // Create connection objects const con = mysql.createConnection(MYSQL_CONF); // Start connecting con.connect(); // Unified execution SQL Function of function exec(sql) { return new Promise((resolve, reject) => { con.query(sql, (err, result) => { if (err) { console.error(err); return; } resolve(result); }); }); } module.exports = { exec, };
4. API docking MySQL( Blog list )
After writing as above , One thing to keep in mind is that , perform SQL Statement returns promise, So get then perhaps await Then we can get the data .
// router/blog.js
// Get a list of blogs
if (method === "GET" && req.path === "/api/blog/list") {
const author = req.query.author || "";
const keyword = req.query.keyword || "";
const result = getList(author, keyword);
// return promise
return result.then((listData) => {
return new SuccessModel(listData);
});
}
// controller/blog.js
const getList = (author, keyword) => {
let sql = `select id, title, content, createtime, author from blogs where 1 = 1`;
if (author) {
sql += ` and author = '${
author}'`;
}
if (keyword) {
sql += ` and title like '%${
keyword}%'`;
}
sql += ` order by createTime desc;`;
return exec(sql);
};
5. API docking MySQL( Blog list details )
// router/blog.js
// Get blog details
if (method === "GET" && req.path === "/api/blog/detail") {
const result = getDetail(id);
return result.then((data) => {
return new SuccessModel(data);
});
}
// controller/blog.js
const getDetail = (id) => {
const sql = `select id, title, content, createTime, author from blogs where id = '${
id}'`;
return exec(sql).then((rows) => {
// It's an array , Extract the first item in the array
return rows[0];
});
};
5. API docking MySQL ( New blog )
// router/blog.js
// Create a new blog
if (method === "POST" && req.path === "/api/blog/new") {
// To create a new blog, you need to get author, But now the login function is not finished , Not yet
req.body.author = "zhangssan";
const result = newBlog(req.body);
return result.then((data) => {
return new SuccessModel(data);
});
}
// controller/blog.js
const newBlog = (blogData = {
}) => {
// blogData Is a blog object , contain title、content、author attribute
blogData = {
...blogData,
createTime: Date.now(),
id: 3, // Indicates a new blog , Inserted into the data table id
};
const {
title, content, author, createTime } = blogData;
const sql = ` insert into blogs (title, content, createTime, author) values ('${
title}', '${
content}', ${
createTime}, '${
author}');`;
return exec(sql).then((insertData) => {
// promise Returns the inserted value corresponding to id
return {
id: insertData.insertId,
};
});
};
6. API docking MySQL( Update blog )
// router/blog.js
// Update a blog
if (method === "POST" && req.path === "/api/blog/update") {
const result = updateBlog(id, req.body);
return result.then((val) => {
if (val) {
return new SuccessModel();
} else {
return new ErrorModel(" Failed to update blog ");
}
});
}
// controller/blog.js
const updateBlog = (id, blogData = {
}) => {
const {
title, content } = blogData;
const sql = ` update blogs set title = '${
title}', content = '${
content}' where id = ${
id} `;
return exec(sql).then((updatedData) => {
if (updatedData.affectedRows > 0) {
return true;
}
return false;
});
};
7. API docking MySQL( Delete blog )
// router/blog.js
// Delete a blog
if (method === "POST" && req.path === "/api/blog/del") {
// Login function is not completed , First use false data
const author = "zhangsan";
const result = delBlog(id, author);
return result.then((val) => {
if (val) {
return new SuccessModel();
} else {
return new ErrorModel(" Failed to delete blog ");
}
});
}
// controller/blog.js
const delBlog = (id, author) => {
const sql = ` delete from blogs where id = '${
id}' and author = '${
author}'; `
return exec(sql).then((delData) => {
if (delData.affectedRows > 0) {
return true;
}
return false;
});
};
8. API docking MySQL( The user login )
// controller/user.js
const loginCheck = (username, password) => {
const sql = ` select username, realname from users where username = '${
username}' and password = '${
password}'; `;
return exec(sql).then((rows) => {
return rows[0] || {
};
});
};
// router/user.js
// Sign in
if (method === "POST" && req.path === "/api/user/login") {
const {
username, password } = req.body;
const result = loginCheck(username, password);
return result.then((data) => {
if (data.username) {
return new SuccessModel();
}
return new ErrorModel(" Login failed ");
});
}
Because of the above router It's all back promise, The previous false data is synchronized , therefore router The returned data needs to pass then perhaps await receive .
// app.js
const serverHandle = async (req, res) => {
// Set the return format JSON
res.setHeader("Content-type", "application/json");
// obtain path
const url = req.url;
req.path = url.split("?")[0];
// analysis query
req.query = qs.parse(url.split("?")[1]);
// analysis POST data Put it after req.body Inside
const postData = await getPostData(req);
req.body = postData;
// Handle blog route
const blogData = await handleBlogRouter(req, res);
if (blogData) {
res.end(JSON.stringify(blogData));
// Need to be return, Otherwise, it will continue to execute
return;
}
// Handle user route
const userData = await handleUserRouter(req, res);
if (userData) {
res.end(JSON.stringify(userData));
return;
}
// Missed route : Plain text returns 404 Information
res.writeHead(404, {
"content-type": "text/plain" });
res.write("404 not found");
res.end();
};
边栏推荐
- Configuration file converted from Excel to Lua
- UCF(暑期团队赛二)
- EditorUtility.SetDirty在Untiy中的作用以及应用
- nacos-高可用seata之TC搭建(02)
- Summary of redis AOF and RDB knowledge points
- RT thread analysis log system RT_ Kprintf analysis
- Fuzzy -- basic application method of AFL
- Vite configures the development environment and production environment
- Postman pre script - global variables and environment variables
- February 12 relativelayout
猜你喜欢
Flody的应用
Steady, 35K, byte business data analysis post
Golang -- TCP implements concurrency (server and client)
Compilation et connexion de shader dans games202 - webgl (comprendre la direction)
Figure database ongdb release v-1.0.3
Why does MySQL need two-phase commit
Basic knowledge and examples of binary tree
剑指 Offer II 039. 直方图最大矩形面积
Talking about the type and function of lens filter
GAMES202-WebGL中shader的编译和连接(了解向)
随机推荐
2021 RoboCom 世界机器人开发者大赛-本科组(复赛)
Oracle deletes duplicate data, leaving only one
Rce code and Command Execution Vulnerability
Hometown 20 years later (primary school exercises)
指針經典筆試題
Mysql高级篇学习总结9:创建索引、删除索引、降序索引、隐藏索引
Modbus protocol communication exception
Summary of redis basic knowledge points
Codeforces Round #804 (Div. 2)
树莓派3.5寸屏幕白屏显示连接
Excel转换为Lua的配置文件
2021RoboCom机器人开发者大赛(初赛)
集合详解之 Collection + 面试题
SQLite add index
Quelques conseils communs sur l'inspecteur de l'unit é, généralement pour les extensions d'éditeur ou d'autres
[lgr-109] Luogu may race II & windy round 6
Leetcode 186 Flip the word II in the string (2022.07.05)
Configuration file converted from Excel to Lua
A little knowledge of CPU, disk and memory
GAMES202-WebGL中shader的編譯和連接(了解向)