Mysql database-----statistics, sorting, paging, addition, deletion, modification, query + operation database in Node

Three ways to enter mysql

1. mysql command interactive tool
Insert picture description here
Enter the password and press Enter
* The password must be in English when entering the password, otherwise a flashback will occur
Insert picture description here

2.cmd to call up the console
There are two types, one requires a password, the other does not need to
enter mysql in 2.1, and does not require an account password. This is two different libraries and is not commonly used.
Insert picture description here

2.2 Enter mysql- uroot -p and press Enter, note that the space
*-u represents the user name, and the default root user name is generally used later, and -p represents the password
Insert picture description here

If the following error occurs, the environment variable is not set.
Insert picture description here
Open Control Panel>System Settings
Insert picture description here
Insert picture description here
Insert picture description here

3. Navicat visualized operation database

Insert picture description here

Click on the connection, a new window will appear, other defaults press OK
Insert picture description here

These are called libraries.A
computer can have many libraries,
a database has multiple tables, and
a table has multiple fields (columns).
Insert picture description here

New database
Insert picture description here

The database name is best in English, and the character set is best to choose utf-8 in order to parse Chinese.
Insert picture description here

Double-click the library to expand, click on the table, create a new database table,
Insert picture description here

Example:
Table Name: name, type is optional, VARCHAR: Representative varying character
table: id, type int,
allowing empty: see their own needs
keys right represents the primary key , on behalf id tag line value unique, not repeated,
may be incremented
when maintaining primary key, because the primary key can not be repeated, maintain up more trouble, so you can use the auto-increment feature allows the system to help maintain
Insert picture description here
the new good after opening, try to enter the same id will prompt an error
Insert picture description here

What problem is the database used to solve?

Function: Organize according to the data structure. The warehouse
nodejs that stores/manages data can also write files with writeFile to achieve the purpose of storing data, but it will be very troublesome to manipulate data in this way. If it is a large website, the data complexity is very high , So it is not displayed with simple file operations.
Data storage is scattered and cannot be centralized management.

Common database classification

Relational database (sql database)

Features: SQL statement can be executed
MySQL: open source database, generally used by Internet companies, the usage rate is very high.
Oracle: large commercial database, many large project banking systems will use Oracle, commercial authorization is very expensive.
Microsoft SQL server: Microsoft developed database, Closed source charges are less expensive.

Non-relational database (No-sql database)

Features: SQL statements cannot be executed.
Mongodlb: A non-relational database that is widely used, and nodejs projects use this database.
Redis: In-memory database, storage is very fast.

Connect and operate the database

SQL statement

Query database list
mysql control window: show databases; display all database lists
* A semicolon must be added to represent the end of the statement to
Insert picture description here
create a database table
Table name: heros

Table fields: id (unique id), name (name, cannot be empty), gender (gender), img (avatar), isdelete (whether to be deleted, default is 0, delete is 1)

//因为id是唯一值,我们设置它为主键,同时我们希望没
//插入一条数据,id值会自动增加1,所以把它设置为自动递增auto_increment
create table heros(
	id int not null primary key auto_increment, 
	name varchar(255) not null, 
	gender varchar(255),
	img varchar(255),
	isdelete tinyint default 0)
	character set utf8;

Enter the database

use 数据库名字;

Delete library command

drop database 删除的库名;

Create database

create database 数据库名字;

When creating a table, you must first tell the database which library to use

user 数据库名字

If no database is selected, it will appear
Insert picture description here

Table structure creation command

create table heros(
	id int not null primary key auto_increment, 
	name varchar(255) not null, 
	gender varchar(255),
	img varchar(255),
	isdelete tinyint default 0)
	character set utf8;

View table structure
desc table name
Insert picture description here

Insert data operation

语法:insert into 表名(字段1,字段2...)value(1,2...);

example:
Insert picture description here

Modify the database

//语法:UPDATE 表名 set 字段1=值1,字段2=值2....where 条件
UPDATE heros set gender = '男'; // 如果后面没有跟条件的话,则表示将表中所有的数据中的gender都改成了男
UPDATE heros set gender = '女' WHERE id = 3; //  将id为3的那条数据中的gender修改为“女”
UPDATE heros set gender = '女' WHERE name = '花木兰'; // 将数据表中名字叫"李四"

delete data

//语法:DELETE FROM 表名 where 条件
DELETE FROM heros where id = 7;
DELETE FROM heros where id = 2 or id = 8;
DELETE FROM heros where id in (4,5,10);
DELETE FROM heros WHERE gender ='男' AND name = '兰陵王';  // 通过多条件来删除数据  and 在这里表示并且的关系 
DELETE FROM heros WHERE id > 10; // 还可以根据id的特性

Check for phrases

//语法:  select * from 表名 where 条件 
select * from  heros;  // 表示查询所有的数据信息
select id,name,gender from heros; // 根据指定的字段来查询
select * from heros where id = 2; //查询id为2的那一条数据
select name,gender from heros where id = 3; // 查询id为3的那条数据中的name gender id
select * from heros where id =3 or id= 5; // 查询id为3 和5 的那两条数据
select * from heros where id = 2 or id = 3 or id = 4;
select * from heros where id in (2,3,4,5,7);  // 查询id为 2  3  4  5  7 的那些数据

Common functions

SQL provides convenient functions for statistics, sorting, etc.

Statistical
count method: used to count the number of query data. Note that the statistical data is not an empty data bar.
MAX: query the largest value
MIN: query the smallest value
avg: query average
* represents all data

SELECT count(字段) FROM 表名;
SELECT MAX(字段) FROM 表名;
SELECT MIN(字段) FROM 表名;
SELECT avg(字段) FROM 表名;

Sort (order by)
default ascending sort, descending plus desc

SELECT * FROM 表名 order by 字段;//默认
SELECT * FROM 表名 order by 字段 desc;

Paging
Function: When you have a lot of databases, you can't get it all at once. You can query the data in batches through paging.
Limit: Indicates how many
items are taken. Offset: Offset, how many items are taken from where to start

select * from 表名 limit 数量
select * from 表名 order by limit 3 offset 2;

Operating database in Node

Node needs to operate the database and needs to rely on mysql third-party libraries

1. The installation of the environment
Create a folder, can not Chinese
Call out the console, enter the npm init project initialization

Example: After a large piece of code appears, press Enter (you can also write) until Is this OK?
Insert picture description here

Install mysql

npm install mysql

example:
Insert picture description here

2. Use
2.1. Create js file to import mysql

const mysql=require('mysql');

2.2. Call mysql.createConnection(()) to get Connection instance

const connection = mysql.createConnection({
    
    
//连接的地址
host:'localhost',
//数据库连接用户名
user:'root',
//密码
password:'写上密码',
//连接的数据库名字
database:'数据库名'
})

The comparison is as follows
Insert picture description here

2.3 Call Connection's connect method to connect to the database

connection.connect();

General example:

const mysql = require('mysql');

const connection = mysql.createConnection({
    
    
    //连接的地址
    host: 'localhost',
    //数据库连接用户名
    user: 'root',
    //密码
    password: 'yinghua3464',
    //连接的数据库名字
    database: 'user'
});
connection.connect();
connection.query('select * from heros', (error, result, filed) => {
    
    
    // console.log(error);//语法是否错误
    console.log(result)//数据内容
    // console.log(filed)
});
//结束
connection.end();

node executes sql statement

Inquire

Call connection.query('sql statement', callback function). The
error parameter is used to indicate whether the sql statement is executed incorrectly. When there is no error, the null value is obtained, otherwise the error message
result indicates the query result, and an array is returned. Is a data object, representing a row of data

connection.query('select * from heros',(error,result,filed)=>{
    
    
console.log(result)
})

Ctrl+`Call up the terminal and enter the node'file name' to see the log results and
Insert picture description here
add data
. After the execution, you can query the data in MySQL

function addHero(id, name, gender, img, isdelete) {
    
    
    // 设置sql语句,添加数据
    //数字不需要''
    const sql = `insert into heros (id,name,gender,img,isdelete) values (${
      
      id},'${
      
      name}','${
      
      gender}','${
      
      img}',${
      
      isdelete})`;
    // 调用query方法query(sql语句,回调函数)
    console.log(sql);
    connection.query(sql, (error, result, filed) => {
    
    
        // 如果error为真则说明有错,则打印
        if (error) {
    
    
            console.log(error);
        } else {
    
    
            // 否则就打印数据
            console.log(result);
        }
    })
};
// 调用函数
addHero(null, '花木兰', '女', 'http://www.baidu.com', 1);

Modify/replace data

function updateHero(name, gender, img, id) {
    
    
    // 设置sql语句,替换数据
    const sql = `update heros set name='${
      
      name}',gender='${
      
      gender}',img='${
      
      img}' where id=${
      
      id}`;
    // 调用query方法query(sql语句,回调函数)
    console.log(sql);
    connection.query(sql, (error, result, filed) => {
    
    
        // 如果error为真则说明有错,则打印
        if (error) {
    
    
            console.log(error);
        } else {
    
    
            // 否则就打印数据
            console.log(result);
        }
    })
}
// 调用函数
updateHero('安其拉', '女', 'http://www.baidu.com', 4);

delete data

function deleteHeroById(id) {
    
    
    // 设置sql语句,删除数据
    const sql = `DELETE FROM heros where id = ${
      
      id};`;
    // 调用query方法query(sql语句,回调函数)
    console.log(sql);
    connection.query(sql, (error, result, filed) => {
    
    
        // 如果error为真则说明有错,则打印
        if (error) {
    
    
            console.log(error);
        } else {
    
    
            // 否则就打印数据
            console.log(result);
        }
    })
}
// 调用函数
deleteHeroById(8);

After execution, you need to call the end method to end the link

connection.end();

Guess you like

Origin blog.csdn.net/weixin_47886687/article/details/108747448