node+mysql+expressBasic

node.js installation

Official website download address: http://nodejs.cn/download/Download
according to requirements, if you need to download other versions:
click all download options, modify the version information on the url route
insert image description here
Installation: one-click installation, remember your installation address
to configure the environment Variables:
1. Directly search for environment variables, click to edit system environment variables (System Properties-Advanced-Environment Variables)
2. System variables – path – select and click Edit – New – copy the installation address – the last three confirmations are required After confirmation,
verify whether the installation is successful:
keyboard win+R, enter cmd command line to open the window, enter node -v to view the nodejs version, enter npm -v to view the npm version, and the displayed version number means the installation is successful

node.js write interface

1. Create an empty folder demo
2. Right-click to open with vscode, click Terminal to create a new terminal
3. Initialize the project npm init, fill in the information as required or press Enter all the way

npm init

3. Download the express framework, body-parser to parse the post request,

npm install express --save
npm install body-parser --save

4. Create a new app.js folder

var express = require('express')
var app = express();

// post请求的中间件(插件,专门用来解析表单 POST 请求体)
let bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({
    
     extended: false }))
app.use(bodyParser.json())

// post请求
app.post('/post', function (req, res) {
    
    
  const data = req.body // 获取入参
  // 对入参做操作......
  const sendData = {
    
    
  	"status": 200,
    "msg": "操作成功",
    "data": ''
  }
  res.send(sendData)
})

// get请求
app.get('/get', function (req, res) {
    
    
  const data = req.query// 获取入参
  // 对入参做操作......
  const sendData = {
    
    
  	"status": 200,
    "msg": "操作成功",
    "data": ''
  }
  res.send(sendData)
})

app.listen(9999,function(){
    
    
    console.log('服务器启动了');
})

mysql installation

  1. Download the MySQL compressed package https://dev.mysql.com/downloads/installer/
  2. Configure mysql:
    1) Decompress the zip file
    2) Put the decompressed compressed package file into the path (do not have a Chinese path) (here I put it under D:) 3
    ) Create a configuration file: in the mysql installation directory, create a my.ini configuration file, and then add the following content in it (mysql installation directory should be changed to your own)
[mysqld]

# 设置3306端口

port=3306

# 设置mysql的安装目录

basedir=D:\mysql-8.0.32-winx64

# 设置mysql数据库的数据的存放目录

datadir=D:\mysql-8.0.32-winx64\data

# 允许最大连接数

max_connections=200

# 允许连接失败的次数。这是为了防止有人从该主机试图攻击数据库系统

max_connect_errors=10

# 服务端使用的字符集默认为UTF8

character-set-server=utf8

# 创建新表时将使用的默认存储引擎

default-storage-engine=INNODB

# 默认使用“mysql_native_password”插件认证

default_authentication_plugin=mysql_native_password

[mysql]

# 设置mysql客户端默认字符集

default-character-set=utf8

[client]

# 设置mysql客户端连接服务端时默认使用的端口

port=3306

default-character-set=utf8

[mysqld]
#查询缓存
explicit_defaults_for_timestamp=true

[mysqld]
# 设置导入导出
secure-file-priv=D:\mysql-8.0.32-winx64\file

4) Configure environment variables: add D:\mysql-8.0.32-winx64\bin to the path

  1. Initialize the mysql database:
    open cmd in the bin directory of mysql, enter: mysqld --initialize-insecure
  2. Install mysql: After
    mysqld -install
    is executed, the prompt Service successfully installed. will appear
  3. Start mysql: After
    net start mysql
    is executed, it shows that the service has started successfully, and the configuration of the server is successful at this point

Mysql common commands

1. Connect to the database:
mysql -u username -p password

2. Display all database names:
show database;

3. Select the library name:
use library name;

4. View all tables:
show tables;

5. Create a library:
create database library name charset utf8;

6. Delete a library:
drop database library name;

7. Create a table:
create table user(
id int(11),
name varchar(25)
);

8. Check the table structure:
desc table name;

9. Modify the table name:
rename table stu to newstu;

10. Delete the table:
drop table table name;

11. Insert data into the table
insert into newstu
(id,name)
values
​​(1,'zhangsan'),
(2,'lisi'),
(3,'wangwu');

11-2. Import data
insert into test.goods
select id,name,count from shop.goods;

12. View all data in the table
select * from newstu;

13. Clear all data in the table
truncate newstu;

14. Solve the garbled characters in the table.
First, look at the format used in the command window, usually gbk;
set names gbk;

15. Store notes and store log information
tee D:\1010.sql

16. Modify the data of the table
update newstu
set name='laoliu'
where id=3;

17. Delete the data of the table
delete from newstu
where id=3;

18. Three major types
Number type:
String type:
Date type:
date–1000-01-01-9999-12-31
time—838:59:59-838:59:59
datetime–1000-01-01 00: 00:00-9999-12-31 23:59:59
year—1901-2155
timestamp
time column to retrieve the current time at any time:
ts timestamp default CURRENT_TIMESTAMP
table creation:
sns social networking site
membership table member
primary key id, user name, gender, weight ( KG), birthday, salary, last login time, personal profile
create table member(
id int unsigned auto_increment primary key,
username char(20) not null default '',
gender char(1) not null default '',
weight tinyint unsigned not null default 0,
birth date not null default '0000-00-00',
salary decimal(8,2) not null default 0.00,
lastlogin int unsigend not null default 0,
intro varchar not null default ‘’
);

19. Modify the table and add
new columns:
alter table table name add username char(20) not null default '';
alter table table name add gender char(1) after username not null default '';
alter table table name add id int not null default 0 first;
delete column:
alter table table name drop username;
modify column type:
alter table table name modify gender char(4) not null default '';
modify column:
alter table table name change username newname char(10) not null default '';

20. Query table
where conditional query
group by grouping
having filter
order by sorting
limit limit the number of results
Basic query practice:
query the details of products whose primary key is 32:
select * from goods where goods_id=32;
find out all products that do not belong to column 3
select * from goods where cat_id!=3; (<>)
query items in column 4 and column 11
select * from goods where cat_id=4 or cat_id=11;
select * from goods where cat_id in (4,11);
query prices
Select * from goods where price between 100 and 500 for goods between 100 and 500;
summary: in is in the collection, between and is in the range, not in is not in the collection

Query mobile phones starting with Nokia
select * from goods where goods_name like 'Nokia%';
Summary: _ matches any single character, % matches any
as rename
interview questions modify part of the data as a base integer
update goods
set count=(count/10) *10
where count between 30 and 50;

Query calculation function:
max, min, sum, svg, count
select max(price) from goods;
select count(1) from goods;

Group calculation:
select goods_id,sum(goods_number) from goods
group by goods_id;

After renaming, having can be found out
. Query the goods whose market price is greater than the sales price and the difference is greater than 200.
select goods_name,(marketprice-price) as diffprice
from goods
where 1
having diffprice>200;

Find out the average score of those who fail more than or equal to 2 gates
select name,avg(score),sum(score<60) as gks
from result
group by name
having gks>=2;

21. Put order by
after group by/where/having
descending desc / ascending asc

22. Paging limit
limit a offset, b takes out the number of entries

23. Subquery
virtual table
exists / does not exist

24、查空 is not null / is null

25. Two table full join query
select a.name,b.name from a,b where a.id=b.id; // no null

26. Left join
a left join b on condition
select a.name,b.name from a left join b on a.id=b.id; // a full check, if b has no corresponding id, fill in null

27. Right join
b right join a on condition (same function as above)

28. Inner connection
a inner join b in condition // Remove all those that do not meet the conditions

node.js sub-module mysql database query encapsulation

  1. Create a new folder, open the terminal, and initialize it (just press Enter all the way)
npm init
  1. Install mysql, express, body-parser
npm i mysql express body-parser

  1. Create a new 1) app.js entry file in the root directory
    2) config folder, used to write database configuration and encapsulate database query
    3) router folder, used to classify the interface of the project
    insert image description here
  2. app.js
// app.js
const express = require('express')
const app = express();

// 导入路由
const loginRouter = require('./router/login')
const tableRouter = require('./router/table')

// post请求 中间件(插件,专门用来解析表单 POST 请求体)
let bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({
    
     extended: false }))
app.use(bodyParser.json())

//引入路由
app.use('/api', loginRouter);// /api/xxxxx
app.use('/api', tableRouter);

var server = app.listen(9999, () => {
    
    
    console.log('服务器启动了');
})
  1. config – db.config.js
// db.config.js
// 创建mysql连接
module.exports = {
    
    
  host: '127.0.0.1', // 服务器地址
  user: 'root', // mysql用户名称
  password: '111111', // mysql用户密码
  port: 3306, // 端口
  database: 'demo1', // 数据库名称
}
  1. config – db.js
// db.js
// 封装 mysql 的语句执行方法
const mysql = require('mysql');
const dbConfig = require('./db.config');

module.exports = {
    
    
    query: function(sql, params, callback) {
    
    
        //每次使用的时候需要创建链接,数据操作完成之后要关闭连接
        const connection = mysql.createConnection(dbConfig)
        connection.connect(function(err) {
    
    
            if (err) {
    
    
                throw err
            }
            //开始数据操作
            connection.query(sql, params, function(err, results, fields) {
    
    
                if (err) {
    
    
                    connection.end(function(err) {
    
    
                        if (err) {
    
    
                            console.log('关闭数据库连接失败!')
                            throw err
                        }
                    })
                    throw err
                }
                //将查询出来的数据返回给回调函数
                callback && callback(
                                results ? JSON.parse(JSON.stringify(results)) : null,
                                fields ? JSON.parse(JSON.stringify(fields)) : null
                            )
                    //停止链接数据库,必须在查询语句后,要不然一调用这个方法,就直接停止链接,数据操作就会失败
                connection.end(function(err) {
    
    
                    if (err) {
    
    
                        console.log('关闭数据库连接失败!')
                        throw err
                    }
                })
            })
        })
    },
}
  1. route r-- login.js
// login.js
const express = require('express')
const db = require('../config/db')
const loginRouter = express.Router()

// 登录post接口
loginRouter.post('/login', function (req, res) {
    
    
  const data = req.body // 获取入参
  let selectSQL = "select userName,password from user where userName = '"+data.username+"' and password = '"+data.password+"'";
  // 查询数据库
  db.query(selectSQL, (err, data) => {
    
    
    if (err) return console.log("查询失败");
    if (data == '') {
    
    
		res.send({
    
    
	        "status": -1,
	        "msg": "账号密码错误",
	        "data": ''
	      })
    } else {
    
    
		res.send({
    
    
	        "status": 200,
	        "msg": "登录成功!",
	        "data": ''
	      })
    }
  })
})
 
module.exports = loginRouter
  1. route r-- table.js
// table.js
const express = require('express')
const db = require('../config/db')
const tableRouter = express.Router()

// 查询商品列表post接口
tableRouter.post('/getList', function (req, res) {
    
    
  const data = req.body // 获取入参
  let selectSQL = `select * from t_table where title like "%${
      
      data.title}%" or content like "%${
      
      data.title}%"`;
  // 查询数据库
  db.query(selectSQL, (err, data) => {
    
    
    if (err) return console.log("查询失败");
    res.send({
    
    
      "status": 200,
      "msg": "操作成功",
      "data": data
    })
  })
})

// 查询权限字典get接口
tableRouter.get('/getList', function (req, res) {
    
    
  let selectSQL = `select * from t_role`;
  // 查询数据库
  db.query(selectSQL, (err, data) => {
    
    
    if (err) return console.log("查询失败");
    console.log("查询成功!");
    res.send({
    
    
      "status": 200,
      "msg": "操作成功",
      "data": data
    })
  })
})

module.exports = tableRouter
  1. start service
node app.js
  1. Go to the browser to access, and the interface result can be displayed normally, as shown in the figure below:

Guess you like

Origin blog.csdn.net/qq_41329287/article/details/128966853