search
HomeDatabaseMysql TutorialWhat are the basic operation methods of node.js for database MySQL?

Basic operations of database MySQL (add, delete, modify, query)

The unified table structure of the entire blog is:
The users table has four fields id username password status, and the four fields represent four columns, among which id It is an auto-increment column, the default value of status is 0, optional value 0, 1
id auto-increment, username is zs, ls, wu password respectively: 123456 abcdef 123abc status is 0, 1, 1

#查询整张表的所有数据
select * from users

#查询指定列的所有数据
select username,password from users

#指定某列添加数据
insert into users(username,password) values('萧寂','1234')

#指定某列修改数据
update users set username="你好a",password="1234567",status=1 where id=2

#根据id删除行
delete from users where id=4

#查询status为1的所有用户
SELECT *FROM users WHERE status=1

#查询id 大于2的所有用户
SELECT *FROM users WHERE id>2

#查询username不等于admin的所有用户
SELECT *FROM users WHERE username<>&#39;admin&#39;

#使用AND来显示所有status为0,并且id 小于3的用户:
SELECT * FROM users WHERE status=0 AND id<3

#使用OR来显示所有status为1,或者username为zs的用户
SELECT* FROM users WHERE status=1 OR username=&#39;zs&#39;

#对users表中的数据,按照status字段进行升序排序
SELECT * FROM users ORDER BY status;(升序排序在status后加上ASC效果等同)
select * from users order by status asc

#根据id降序排序,降序排序使用desc关键字
select * from users order by id desc

#多重排序 对users 表中的数据,先按照status字段进行降序排序,再按照username的字母顺序,进行升序排序
SELECT * FROM users ORDER BY status DESC,username asc

#查询id为1的数据返回的总条数
select count(*) from users where id=1

#将列名称从COUNT(*)修改为total
SELECT COUNT(*) AS total FROM users WHERE id=1

#给username列添加uname别名,给password列添加upwd别名
select username as uname,password as upwd from users

Add, delete, modify and check in node.js project

First execute the command to initialize the package.json package

npm init -y  (文件名为英文,不能有空格、特殊字符或中文,否则报错)

mysql module is managed Third-party modules on npm. It provides the ability to connect and operate MySQL database in Node.js projects.
If you want to use it in the project, you need to run the following command first to install mysql as a dependency package of the project:

npm install mysql   或者  npm i mysql

After the above operation is completed, start configuring the MySQL module

Configuring the MySQL module

Before using the mysql module to operate the MySQL database, you must first perform the necessary configuration on the mysql module. The main configuration steps are as follows:

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

Test whether the module can Whether the connection works normally (execute the run command node file name or nodemon file name)

Call the db.query() function, specify the SQL statement to be executed, and get it through the callback function The execution result

db.query("select 1", function (err, results) {
    //模块报错返回错误信息
    if (err) return console.log(err.message);
    //运行成功
    console.log(results);
})

The return result of a successful test is: [ RowDataPacket { ‘1’: 1 } ]

The SQL code of the query table ( See the first line for table name and structure)

查询数据user表中所有的用户数据
const sqlStr = "select * from users"
db.query(sqlStr, function (err, results) {
    //查询失败
    if (err) return console.log(err.message);
    //查询成功
    //注意如果执行的是select查询语句,则执行的结果是数组
    console.log(results);
})

SQL statement to add data (two methods)

//插入数据
//向users表中新增数据,其中username为Spider-Man,password为pcc321
//要插入到users表中的数据对象
const user = { username: "Spider-Man", password: "pcc321" }
//待执行的SQL语句,其中的?表示占位符
const sqlStr = "insert into student(student,card) values(?,?)"
//使用数组的形式,依次为?占位符具体的值(result.affectedRows为影响的行数)
db.query(sqlStr, [user.username, user.password], function (err, results) {
    if (err) return console.log(err.message);
    if (results.affectedRows == 1) {
        console.log("插入成功");
    }
})
//向表中新增数据时,如果数据对象的每个属性和数据表的字段一一对应,则可以通过如下方式快速插入数据:
//要插入到users表中的数据对象
const user = { username: "Spider2-Man", password: "pcc321" }
//待执行的SQL语句,其中的?表示占位符
const sqlStr = "insert into users set ?"
db.query(sqlStr, user, function (err, results) {
    if (err) return console.log(err.message);
    if (results.affectedRows == 1) {
        console.log("插入成功");
    }
})

SQL statement to modify data (two methods)

//修改表中的数据
//向users表中更新的数据,其中username为Spider-Man,password为pcc321,id为5
const user = { id: 7, username: "xiao1jiao", password: "111222" }
//待执行的sql语句,其中的?表示占位符
const sqlStr = "update users set username=?,password=? where id=?"
//使用数组的形式,依次为?占位符具体的值(result.affectedRows为影响的行数)
db.query(sqlStr, [user.username, user.password, user.id], function (err, results) {
    if (err) return console.log(err.message);
    if (results.affectedRows == 1) {
        console.log("修改", user.id, "列成功");
    }
})
//修改表数据时,如果数据对象的每个属性和数据表的字段一一对应,则可以通过如下方式快速修改表数据
//向users表中更新的数据,其中username为aaaa,password为1111,id为5
const user = { id: 5, username: "aaaa", password: "1111" }
//待执行的sql语句,其中的?表示占位符
const sqlStr = "update users set ? where id=?"
//使用数组的形式,依次为?占位符具体的值(result.affectedRows为影响的行数)
db.query(sqlStr, [user, user.id], function (err, results) {
if (err) return console.log(err.message);
if (results.affectedRows == 1) {
    console.log("修改", user.id, "列成功");
}
})

Delete SQL statement of data

//在删除数据时,推荐根据id这样的唯一标识,来删除对应的数据。示例如下:
const sqlStr = "delete from users where id=?"
//调用db.query(O)执行SQL语句的同时,为占位符指定具体的值
//注意:如果SQL语句中有多个占位符,则必须使用数组为每个占位符指定具体的值
//如果SQL语句中只有一个占位符,则可以省略数组
db.query(sqlStr, 5, function (err, results) {
    if (err) return console.log(err.message);
    //注意:执行 delete语句之后,结果也是一个对象,也会包含 affectedRows属性
    if (results.affectedRows == 1) {
        console.log("删除成功");
    }
})

Mark deletion situation

//标记删除
//使用DELETE语句,会把真正的把数据从表中删除掉。为了保险起见,推荐使用标记删除的形式,来模拟删除的动作。
//所谓的标记删除,就是在表中设置类似于status这样的状态字段,来标记当前这条数据是否被删除。
//当用户执行了删除的动作时,我们并没有执行DELETE语句把数据删除掉,而是执行了UPDATE语句,将这条数据对应的status字段标记为删除即可。
//标记删除:使用 UPDATE语句替代 DELETE语句;只更新数据的状态,并没有真正删除
const sqlStr = "update users set status=? where id=?"
db.query(sqlStr, [0, 7], function (err, results) {
    if (err) return console.log(err.message);
    if (results.affectedRows == 1) {
        console.log("标记删除成功");
    }
})

Note: The placeholder marking method mentioned in the article has better compatibility. The author has done tests and used native SQL After the statement is spliced ​​into fields, it is directly executed using the db.query statement. As a result, an error is reported when processing rich text data, and character escaping is required. This will not happen when using ? placeholder.

The above is the detailed content of What are the basic operation methods of node.js for database MySQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Explain the InnoDB Buffer Pool and its importance for performance.Explain the InnoDB Buffer Pool and its importance for performance.Apr 19, 2025 am 12:24 AM

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

MySQL vs. Other Programming Languages: A ComparisonMySQL vs. Other Programming Languages: A ComparisonApr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Learning MySQL: A Step-by-Step Guide for New UsersLearning MySQL: A Step-by-Step Guide for New UsersApr 19, 2025 am 12:19 AM

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.

MySQL: Essential Skills for Beginners to MasterMySQL: Essential Skills for Beginners to MasterApr 18, 2025 am 12:24 AM

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL: Structured Data and Relational DatabasesMySQL: Structured Data and Relational DatabasesApr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL: Key Features and Capabilities ExplainedMySQL: Key Features and Capabilities ExplainedApr 18, 2025 am 12:17 AM

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

The Purpose of SQL: Interacting with MySQL DatabasesThe Purpose of SQL: Interacting with MySQL DatabasesApr 18, 2025 am 12:12 AM

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

MySQL for Beginners: Getting Started with Database ManagementMySQL for Beginners: Getting Started with Database ManagementApr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.