Table of Contents
Database
MySQL installation and configuration
WHERE clause
AND和OR
ORDER BY子句
COUNT(*)函数
在Express项目中操作MySQL
Home Web Front-end JS Tutorial Let's talk about how to operate MySQL in Node project

Let's talk about how to operate MySQL in Node project

Jan 09, 2023 am 10:36 AM
mysql nodejs node

How to operate MySQL in Node project? The following article will talk to you about several SQL statements for managing databases, and introduce how to operate MySQL in Express projects. I hope it will be helpful to you!

Let's talk about how to operate MySQL in Node project

Database


Database is used to organize, A warehouse that stores and manages data. Today's world is an Internet world full of data, full of a large amount of data. There are many sources of data, such as travel records, consumption records, web pages browsed, messages sent, etc. In addition to text type data, images, music, and sounds are all data. In order to facilitate the management of data in the Internet world, there is the concept of database management system (referred to as: database). Users can perform operations such as adding, querying, updating, and deleting data in the database.

Classification of database:

MySQL database(currently The most widely used and popular open source free database; Community Enterprise)

Oracle Database(Paid)

SQL Server database (charged)

Mongodb database(Community Enterprise)

Comparison: MySQL, Oracle, and SQL Server are traditional databases (also called: relational databases or SQL databases). These three have the same design concept and similar usage; while MongoDB is a new type of database (also called: non-relational databases or NoSQL databases). ), which makes up for the shortcomings of traditional databases to a certain extent.

Data organization structure of traditional database: In traditional database, the data organization structure is divided into database (database), data table (table) ), data row (row), and field (field).

The relationship between libraries, tables, rows, and fields in actual development: In actual project development, generally, each project corresponds to an independent database;Different data should be stored in different tables of the database, for example: user data is stored in the users table, and book data is stored in the books table;The specific information stored in each table is determined by the fields. For example: we can design the three fields of id, username, and password for the users table; table The rows in represent each specific piece of data.

MySQL installation and configuration

For developers, they only need to install MySQL Server and Navicat to meet their development needs.

MySQL Server: Software specially used to provide data storage and services

Navicat: A visual MySQL management tool through which you can conveniently operate the data stored in MySQL Server

For specific installation tutorials, please refer to my previous article: MySQL Installation. With visualization tools, it becomes extremely easy for us to create tables and edit table data.

##SQL management database

SQL (full English name: Structured Query Language) is

Structured Query Language, a programming language specifically used to access and process databases. It allows us to manipulate the data in the database in the form of programming.

Note:

1) SQL is a database programming language

2) Written in SQL language The code that comes out is called a SQL statement

3) SQL language can only be used in relational databases (for example: MySQL, Oracle, SQL server). Non-relational databases (such as Mongodb) do not support SQL language.

SELECT statement

is used to query data from the table. The results of the execution are stored in a results table (called a result set). The syntax is as follows: (Note: Keywords in SQL statements are not case-sensitive, SELECT is equivalent to select, and FROM is equivalent to from).

-- 这是注释
-- 从 FROM 指定的【表中】,查询出【所有的】数据,* 表示【所有列】
SELECT * FROM 表名称

-- 从 FROM 指定的【表中】,查询出指定 列名称 (字段) 的数据
SELECT 列名称 FROM 表名称
Copy after login

INSERT INTO statement

is used to insert data Insert new data rows into the table.

-- 向指定表中插入数据,列的值通过 values 一一指定
-- 列和值要一一对应,多个列和多个值之间,要使用英文逗号分隔
insert into table_name (列1,列2...) values (值1,值2,值3)
Copy after login

Update statement

is used to modify the data in the table

-- 用 UPDATE 指定要更新哪个表中的数据,用 SET 指定列对应的新值,用 WHERE 指定更新的条件
update 表名称 set 列名称 = 新值 where 列名称 = 某值
Copy after login

DELETE statement

is used to delete rows in the table

-- 从指定的表中,根据 WHERE 条件,删除对应的数据行
delete from 表名称 where 列名称 = 值
Copy after login

WHERE clause

is used to limit the selection criteria. In SELECT, UPDATE, and DELETE statements, the WHERE clause can be used to limit the selection criteria.

-- 查询语句中的 WHERE 条件
select 列名称 from 表名称 where 列 运算符 值
-- 更新语句中的 WHERE 条件
update 表名称 set 列=新值 where 列 运算符 值
-- 删除语句中的 WHERE 条件
delete from 表名称 where 列 运算符 值
Copy after login

The following operators can be used in the WHERE clause to limit the selection criteria:

##<> (this is possible in some versions of SQL Written as != ) is not equal to > is greater than ##<>=<=BETWEEN##LIKE
Operator Description
= is equal to
Less than
Greater than or equal to
Less than Equal
Search for a certain pattern within a certain range
#

例如:可以通过 WHERE 子句来限定 SELECT 的查询条件:

-- 查询 status 为 1 的所有用户
select * from users where status=1
-- 查询 id 大于 2 的所有用户
select * from users where id>2
-- 查询 username 不等于 admin 的所有用户
select * from users where username<>'admin'<h3 id="strong-AND和OR-strong"><strong>AND和OR</strong></h3>
<p>AND和OR可在WHERE子语句中把两个或多个条件结合起来。</p>
<p>AND表示必须同时满足多个条件,相当于JS中的 && 运算符</p>
<p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/024/3cc06dc44f0b2b5dc86f5fb3b6881a23-7.png" class="lazy" alt=""    style="max-width:90%"  style="max-width:90%"></p>
<p>OR表示只要满足任意一个条件即可,相当于JS中的 || 运算符</p>
<p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/024/6a919fc9198576ce31b07caef123af2d-8.png" class="lazy" alt=""    style="max-width:90%"  style="max-width:90%"></p>
<h3 id="strong-ORDER-BY子句-strong"><strong>ORDER BY子句</strong></h3>
<p>order by语句用于根据指定的列对结果集进行排序。order by语句默认按照升序对记录进行排序,如果想按照降序对记录进行排序,可以使用<span style="color:#be191c;"><strong> DESC </strong></span>关键字。</p>
<p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/024/4e55a89f9c966a3ffd3ee77fe6029c34-9.png" class="lazy" alt=""    style="max-width:90%"  style="max-width:90%"></p>
<p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/024/4e55a89f9c966a3ffd3ee77fe6029c34-10.png" class="lazy" alt=""    style="max-width:90%"  style="max-width:90%"></p>
<p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/024/2f7c5c3574ca21ce011ca58d2e53e002-11.png" class="lazy" alt=""    style="max-width:90%"  style="max-width:90%"></p>
<h3 id="strong-COUNT-函数-strong"><strong>COUNT(*)函数</strong></h3>
<p><span style="color:#be191c;"><strong>COUNT(*)</strong></span>函数用于<span style="color:#b95514;"><strong>返回查询结果的总数据条数</strong></span>,语法格式如下:</p>
<p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/024/2f7c5c3574ca21ce011ca58d2e53e002-12.png" class="lazy" alt=""    style="max-width:90%"  style="max-width:90%"></p>
<p>使用AS为列设置别名:如果希望给查询出来的列名设置别名,可以使用 AS 关键字:</p>
<p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/024/9b76d8432b5c57738c0bf5ccbac1cd83-13.png" class="lazy" alt=""    style="max-width:90%"  style="max-width:90%"></p>
<h2 id="strong-在Express项目中操作MySQL-strong"><strong>在Express项目中操作MySQL</strong></h2>
<p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/024/9b76d8432b5c57738c0bf5ccbac1cd83-14.png" class="lazy" alt=""    style="max-width:90%"  style="max-width:90%"></p>
<p><span style="color:#be191c;"><strong>安装操作MySQL数据库的第三方模块(mysql)</strong></span>:</p>
<p>mysql模块是托管于npm上的第三方模块。它提供了在 Node.js项目中连接和操作MySQL数据库的能力。想要在项目中使用它,需要先运行如下命令,将mysql安装为项目的依赖包:(<span style="color:#be191c;"><strong>注意</strong></span>:如果数据库是8.0以后的,需安装mysql2,因为8.0+版本的加密方式改变,node目前还不支持!)【相关教程推荐:<a href="https://www.php.cn/course/list/24.html" target="_blank">nodejs视频教程</a>、<a href="https://www.php.cn/course.html" target="_blank" textvalue="编程教学">编程教学</a>】</p>
<pre class="brush:php;toolbar:false"># 我的数据库是8.0+版本,安装如下命令即可
npm install mysql2
Copy after login

通过mysql模块连接到MySQL数据库

在使用mysql模块操作 MySQL数据库之前,必须先对 mysql模块进行必要的配置,主要的配置步骤如下:

// 导入 mysql 模块
const mysql = require('mysql2')
// 建立与MySQL数据库的连接
const db = mysql.createPool({
  host:'127.0.0.1',    // 数据库的 IP 地址
  port:'3306'          // 数据库的端口号
  user:'root',         // 登录数据库的账号
  password:'123456',   // 登录数据库的密码
  database:'mysql_test'// 指定要操作哪个数据库
})
Copy after login

通过mysql模块执行SQL语句

调用 db.query() 函数,指定要执行的SQL语句,通过回调函数拿到执行的结果:

// 导入 mysql 模块
const mysql = require('mysql2')
// 建立与MySQL数据库的连接
const db = mysql.createPool({
  host:'127.0.0.1',    // 数据库的 IP 地址
  port:'3306',
  user:'root',         // 登录数据库的账号
  password:'123456',   // 登录数据库的密码
  database:'mysql_test'// 指定要操作哪个数据库
})

// 检测 mysql 模块能否正常执行
db.query('select * from users',(err,results)=>{
  if(err) return console.log(err.message);
  // 只要能打印出 [RowDataPacket {'1','1'} ]的结果,就证明数据库连接正常
  console.log(results);
})
Copy after login

向 users 表中新增数据,其中username为张三,password为123000,代码如下:

// 向数据库中添加数据
const thing = {username:'hh',password:123000}
// 待执行的SQL语句,其中英文 ? 表示占位符s
// const dataStr = 'insert into users (username,password) values (?,?)'

// 向表中增添数据时,如果数据对象的每个属性和数据表字段一一对应,则可以通过以下方式简单快速插入语句
const dataStr = 'insert into users set ?'

// 使用数组形式,为 ? 占位符指定具体的值
// db.query(dataStr,[thing.username,thing.password],(err,results)=>{
  
db.query(dataStr,thing,(err,results)=>{
  if(err) return console.log(err.message); // 失败
  // 注意:如果执行的是insert into插入语句,则results是一个对象
  // 可以通过affectedRows属性,来判断是否插入数据成功
  if(results.affectedRows === 1){
     console.log('数据插入成功!');
  }
})
Copy after login

因为 id 具有唯一性,即使你把某条id的记录删掉,它的id下一条数据是用不了的,只能自增。

更新数据对象,可以通过以下方式进行:

// 向数据库中更新数据
const thing = {id:3,username:'aaa',password:123000}
// 待执行的SQL语句,其中英文 ? 表示占位符s
const dataStr = 'update users set username=?,password=? where id=?'
// 调用db. query()执行SQL语句的同时,使用数组依次为占位符指定具体的值
db.query(dataStr,[thing.username,thing.password,thing.id],(err,results)=>{
  if(err) return console.log(err.message); // 失败
  // 可以通过affectedRows属性,来判断是否更新数据成功
  if(results.affectedRows === 1){
     console.log('数据更新成功!');
  }
})
Copy after login

删除数据时,推荐用唯一标识 id 去删除。

// 向数据库中删除数据
const dataStr = 'delete from users where id=?'
db.query(dataStr,4,(err,results)=>{
  if(err) return console.log(err.message); // 失败
  // 可以通过affectedRows属性,来判断是否删除数据成功
  if(results.affectedRows === 1){
     console.log('数据删除成功!');
  }
})
Copy after login

标记删除:使用DELETE语句,会把真正的把数据从表中删除掉。为了保险起见,推荐使用标记删除的形式,来模拟删除的动作。所谓的标记删除,就是在表中设置类似于status这样的状态字段,来标记当前这条数据是否被删除。当用户执行了删除的动作时,我们并没有执行DELETE语句把数据删除掉,而是执行了UPDATE语句,将这条数据对应的status字段标记为删除即可。

// 标记删除:使用 update 语句来替代 delete 语句,只更新数据的状态,并没有真正删除
const dataStr = 'update users set status=1 where id=?'
db.query(dataStr,11,(err,results)=>{
  if(err) return console.log(err.message); // 失败
  // 可以通过affectedRows属性,来判断是否删除数据成功
  if(results.affectedRows === 1){
     console.log('数据删除成功!');
  }
})
Copy after login

更多node相关知识,请访问:nodejs 教程

The above is the detailed content of Let's talk about how to operate MySQL in Node project. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

How to open phpmyadmin How to open phpmyadmin Apr 10, 2025 pm 10:51 PM

You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

How to create navicat premium How to create navicat premium Apr 09, 2025 am 07:09 AM

Create a database using Navicat Premium: Connect to the database server and enter the connection parameters. Right-click on the server and select Create Database. Enter the name of the new database and the specified character set and collation. Connect to the new database and create the table in the Object Browser. Right-click on the table and select Insert Data to insert the data.

MySQL and SQL: Essential Skills for Developers MySQL and SQL: Essential Skills for Developers Apr 10, 2025 am 09:30 AM

MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.

How to create a new connection to mysql in navicat How to create a new connection to mysql in navicat Apr 09, 2025 am 07:21 AM

You can create a new MySQL connection in Navicat by following the steps: Open the application and select New Connection (Ctrl N). Select "MySQL" as the connection type. Enter the hostname/IP address, port, username, and password. (Optional) Configure advanced options. Save the connection and enter the connection name.

How to recover data after SQL deletes rows How to recover data after SQL deletes rows Apr 09, 2025 pm 12:21 PM

Recovering deleted rows directly from the database is usually impossible unless there is a backup or transaction rollback mechanism. Key point: Transaction rollback: Execute ROLLBACK before the transaction is committed to recover data. Backup: Regular backup of the database can be used to quickly restore data. Database snapshot: You can create a read-only copy of the database and restore the data after the data is deleted accidentally. Use DELETE statement with caution: Check the conditions carefully to avoid accidentally deleting data. Use the WHERE clause: explicitly specify the data to be deleted. Use the test environment: Test before performing a DELETE operation.

How to use single threaded redis How to use single threaded redis Apr 10, 2025 pm 07:12 PM

Redis uses a single threaded architecture to provide high performance, simplicity, and consistency. It utilizes I/O multiplexing, event loops, non-blocking I/O, and shared memory to improve concurrency, but with limitations of concurrency limitations, single point of failure, and unsuitable for write-intensive workloads.

phpmyadmin connection mysql phpmyadmin connection mysql Apr 10, 2025 pm 10:57 PM

How to connect to MySQL using phpMyAdmin? The URL to access phpMyAdmin is usually http://localhost/phpmyadmin or http://[your server IP address]/phpmyadmin. Enter your MySQL username and password. Select the database you want to connect to. Click the "Connection" button to establish a connection.

See all articles