• Node.js Video Tutorials

Node.js - MySQL 更新



数据驱动的 Node.js 应用程序通常需要修改存储在 MySQL 数据库中的一条或多条记录。这是通过将 UPDATE 查询字符串作为参数传递给 mysql.query() 方法来完成的。通常,现有记录的数据需要更新,以用户输入的形式出现,例如 Node.js 基于 Web 的应用程序中发布的 HTML 表单。在本章中,您将学习如何执行 MySQL UPDATE 查询。从简单的 UPDATE 开始,使用预处理语句和带有 JOIN 的 UPDATE 将通过合适的 Node.js 示例进行演示。

简单 UPDATE

MySQL 中基本 UPDATE 语句的语法如下:

UPDATE table_name 
SET 
   column_name1 = expr1, column_name2 = expr2,  ...
WHERE condition;

假设 MySQL 服务器上有一个名为 mydb 的数据库,并且 employee 表存在以下数据:

mysql> select * from employee;
+----+-------+------+--------+
| id | name  | age  | salary |
+----+-------+------+--------+
|  1 | Ravi  |   25 |  25000 |
|  2 | Anil  |   26 |  30000 |
|  3 | Meena |   26 |  27000 |
+----+-------+------+--------+

示例

以下程序更新 employee 表的 salary 字段,将每个员工的工资增加 500 元

var mysql = require('mysql');
var con = mysql.createConnection({
   host: "localhost",
   user: "root",
   password: "mypassword",
   database: "mydb"
});

var qry ="UPDATE employee SET salary=salary+500;";
con.connect(function (err) {
   if (err) throw err;
   console.log("Connected!");
   con.query(qry, function(err) {
      if (err) throw err;
      console.log("Records updated successfully");
   });
});

运行以上代码后,转到 MySQL 命令行客户端并检查 employee 表中的行:

mysql> select * from employee;
+----+-------+------+--------+
| id | name  | age  | salary |
+----+-------+------+--------+
|  1 | Ravi  |   25 |  25500 |
|  2 | Anil  |   26 |  30500 |
|  3 | Meena |   26 |  27500 |
+----+-------+------+--------+

您也可以在代码中添加如下循环以查看员工记录

qry =`SELECT name,salary FROM employee;`;
con.query(qry, function (err, results) {
   if (err) throw err;
   console.log(results);
});

输出

[
  RowDataPacket { name: 'Ravi', salary: 25500 },
  RowDataPacket { name: 'Anil', salary: 30500 },
  RowDataPacket { name: 'Meena', salary: 27500 }
]

使用预处理语句进行 UPDATE

MySQL 支持预处理语句。您可以通过在查询字符串中嵌入的占位符中插入可变数据来动态构建查询。MySQL 使用 ? 符号作为占位符。

var qry ="UPDATE employee SET salary=40000 WHERE name=?;";
var nm = "Anil";
con.connect(function (err) {
   if (err) throw err;
   console.log("Connected!");
   con.query(qry, nm, function(err) {
      if (err) throw err;
      console.log("Records updated successfully");
      var qry =`SELECT name,salary FROM employee WHERE name=?;`;
      con.query(qry,nm, function (err, results) {
         if (err) throw err;
         console.log(results);
      });
   });
});

这将把名为 Anil 的员工的工资更新为 40000 元

[ RowDataPacket { name: 'Anil', salary: 40000 } ]

UPDATE JOIN

JOIN 子句更常用于 SELECT 查询中,以从两个或多个相关表中检索数据。您也可以在 UPDATE 查询中包含 JOIN 子句,以执行跨表更新。

对于此示例,我们将创建两个具有公共字段的表,以在两个表之间建立 PRIMARY KEY - FOREIGN KEY 关系。

merits 表

CREATE TABLE merits (
   performance INT(11) NOT NULL,
   percentage FLOAT NOT NULL,
   PRIMARY KEY (performance)
);

添加一些数据:

INSERT INTO merits(performance,percentage)
VALUES(1,0),
      (2,0.01),
      (3,0.03),
      (4,0.05),
      (5,0.08);
      (4,0.05),
      (5,0.08);

merits 表的内容:

mysql> select * from merits;
+-------------+------------+
| performance | percentage |
+-------------+------------+
|           1 |          0 |
|           2 |       0.01 |
|           3 |       0.03 |
|           4 |       0.05 |
|           5 |       0.08 |
+-------------+------------+

employees 表

CREATE TABLE employees (
   emp_id INT(11) NOT NULL AUTO_INCREMENT,
   emp_name VARCHAR(255) NOT NULL,
   performance INT(11) DEFAULT NULL,
   salary FLOAT DEFAULT NULL,
   PRIMARY KEY (emp_id),
   CONSTRAINT fk_performance FOREIGN KEY (performance)
      REFERENCES merits (performance)
);

在此表中,performance 是外键,引用 merits 表中相同名称的键。

添加一些数据:

INSERT INTO employees(emp_name,performance,salary)      
VALUES('Mary Doe', 1, 50000),
      ('Cindy Smith', 3, 65000),
      ('Sue Greenspan', 4, 75000),
      ('Grace Dell', 5, 125000),
      ('Nancy Johnson', 3, 85000),
      ('John Doe', 2, 45000),
      ('Lily Bush', 3, 55000);

employees 表的内容:

mysql> select * from employees;
+--------+---------------+-------------+--------+
| emp_id | emp_name      | performance | salary |
+--------+---------------+-------------+--------+
|      1 | Mary Doe      |           1 |  50000 |
|      2 | Cindy Smith   |           3 |  65000 |
|      3 | Sue Greenspan |           4 |  75000 |
|      4 | Grace Dell    |           5 | 125000 |
|      5 | Nancy Johnson |           3 |  85000 |
|      6 | John Doe      |           2 |  45000 |
|      7 | Lily Bush     |           3 |  55000 |
+--------+---------------+-------------+--------+
7 rows in set (0.00 sec)

我们希望根据与员工绩效评级相关的百分比来增加员工的工资。

示例

var mysql = require('mysql');
var con = mysql.createConnection({
   host: "localhost",
   user: "root",
   password: "mypassword",
   database: "mydb"
});

var qry =`
   UPDATE employees
      INNER JOIN
   merits ON employees.performance = merits.performance 
SET 
   salary = salary + salary * percentage;
   `;
con.connect(function (err) {
   if (err) throw err;
   console.log("Connected!");

   con.query(qry, nm, function(err) {
      if (err) throw err;
      con.query(qry,nm, function (err, results) {
         if (err) throw err;
         console.log(results);
      });
   });
});

输出

OkPacket {
  fieldCount: 0,
  affectedRows: 7,
  insertId: 0,
  serverStatus: 34,
  warningCount: 0,
  message: '(Rows matched: 7  Changed: 6  Warnings: 0',
  protocol41: true,
  changedRows: 6
}

检查 employees 表中更新后的 salary 字段:

mysql> select * from employees;
+--------+---------------+-------------+--------+
| emp_id | emp_name      | performance | salary |
+--------+---------------+-------------+--------+
|      1 | Mary Doe      |           1 |  50000 |
|      2 | Cindy Smith   |           3 |  66950 |
|      3 | Sue Greenspan |           4 |  78750 |
|      4 | Grace Dell    |           5 | 135000 |
|      5 | Nancy Johnson |           3 |  87550 |
|      6 | John Doe      |           2 |  45450 |
|      7 | Lily Bush     |           3 |  56650 |
+--------+---------------+-------------+--------+
7 rows in set (0.00 sec)
广告