本篇文章讲解了 Node.js 连接 MySQL 并实现增删改查功能。
一、设计表
首先通过可视化工具进行表的设计,然后添加几条测试数据:


二、安装 Node.js 连接 MySQL 的包
npm i mysql -d
三、连接 MySQL
MySQL.js
// 引入 mysql 包
const mysql = require('mysql');
// mysql 连接信息
let connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'test',
port: 3306
});
// 开始链接
connection.connect();
// 查询 info_test 表
connection.query('SELECT * FROM info_test', (error, results, fields) => {
if (error) throw error;
console.log(results);
});
// 终止连接
connection.end();
执行 node MySQL.js,连接成功界面如下:

接下来就该实现增删改查的功能了。
四、增删改查
1、增
add.js
const mysql = require('mysql');
let connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'test',
port: 3306
});
connection.connect();
// 设置 SQL 插入语句
let addSql = 'INSERT INTO info_test(id,name,age) VALUES(0,?,?)';
// 插入数据
let addSqlParams = ['zhao', '18'];
// 链接 SQL 并实施语句
connection.query(addSql, addSqlParams, (error, response) => {
if (error) {
console.log("新增失败!");
console.log(error);
return;
} else {
console.log("新增成功!");
console.log(response);
};
});
connection.end();
执行 node add.js

刷新 Navicat,会看到新添加了一条数据。

2、删
delete.js
const mysql = require('mysql');
let connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'test',
port: 3306
});
connection.connect();
// 设置 SQL 删除语句
let delSql = 'DELETE FROM info_test where id=0';
connection.query(delSql, (error, response) => {
if (error) {
console.log("删除失败!");
console.log(error);
return;
} else {
console.log("删除成功!");
console.log(response);
};
});
connection.end();
执行 node delete.js

刷新 Navicat,会看到 id 为 0 的那条数据被删除了。

3、改
update.js
const mysql = require('mysql');
let connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'test',
port: 3306
});
connection.connect();
// 设置 SQL 修改语句
let updateSql = 'UPDATE info_test SET name = ?,age = ? WHERE ID = ?';
// 要修改的数据
let updateSqlParams = ['Wang', '18', 1];
connection.query(updateSql, updateSqlParams, (error, response) => {
if (error) {
console.log("删除失败!");
console.log(error);
return;
} else {
console.log("删除成功!");
console.log(response);
};
});
connection.end();
执行 node update.js

刷新 Navicat,会看到 id 为 1 的那条数据被修改了。

4、查
read.js
const mysql = require('mysql');
let connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'test',
port: 3306
});
connection.connect();
// 设置 SQL 修改语句
let readSql = 'SELECT * FROM info_test';
connection.query(readSql, (error, response) => {
if (error) {
console.log("查询失败!");
console.log(error);
return;
} else {
console.log("查询成功!");
console.log(response);
};
});
connection.end();
执行 node read.js


网友评论