发布于 2026-01-06 1 阅读
0

Beginner's guide to using MySQL database in a Node.js app

Node.js 应用中使用 MySQL 数据库的入门指南

在之前的博客中,我们学习了如何从零开始创建Ruby on RailsNode.js / Express服务器。在这些示例中,我们对服务器中存储在文件中的数据进行了创建 (C)、读取 (R)、更新 (U) 或删除 (D) 操作。

虽然这种方法可能足以处理我们创建的简单教程应用程序的数据,但对于现实生活中的应用程序来说,这并不是管理数据的最佳方法。

想象一下,你创建了下一个亚马逊电商平台。数百万用户将同时访问你的应用程序进行商品买卖。

giphy

你能想象每次有人想买东西都要通读整个数据文件吗?那会耗费大量时间,最终只会让很多顾客感到沮丧!

这时数据库就派上用场了!它专门用于高效地存储和检索数据。

SQL(关系型数据库)和 NoSQL(非关系型数据库)是目前市面上两大主要的数据库类型。本教程将重点介绍 SQL 数据库。

如果你想深入了解 SQL 和 NoSQL 之间的区别及其应用场景,请查看这些资源。我觉得它们很有帮助!

什么是SQL数据库?

顾名思义,SQL 数据库是用 SQL(结构化查询语言)编写的,SQL 是一种用于设计关系数据库的编程语言。

SQL数据库以其预定义的数据模式而闻名,数据模式是一组数据库对象(例如数据表)的集合。在使用数据表之前,我们必须定义它包含哪些列(字段)以及它将存储哪些类型的数据(例如整数、文本等)。

为了存储数据,数据必须满足所有预定义的要求。正如您所见,SQL 数据库的严格规则确保了您在使用不同应用程序或数据库副本时数据的一致性。

SQL 数据库是一种关系型数据库,它存储并提供对彼此相关的数据点的访问(摘自Oracle)。

例如,假设我们正在管理一个团队的项目管理应用程序的数据库。项目管理涉及三个要素:团队成员、项目任务和项目经理。

giphy

如您所见,所有这些因素都相互关联。团队成员可能参与多个项目,一个项目也可能有多位团队成员。团队成员向经理汇报工作,经理负责跟踪每位成员负责的项目任务。

在 SQL 数据库中,每个因素(模型)都会创建一个表。团队成员表包含团队成员的特定信息(ID、姓名和职称)。项目任务表包含任务的特定信息(ID、项目名称、项目详情和截止日期)。只有经理表记录哪个团队成员(团队成员 ID)负责哪个项目(项目 ID),并作为唯一的数据源。所有这些表彼此关联。

我制作了一个表格来帮助你更好地理解这个概念!

替代文字

在许多情况下,记录人际关系会非常有用。

例如,关系型数据库可用于跟踪库存、处理电子商务交易、管理海量关键客户信息等等。任何需要以安全、基于规则且一致的方式管理数据点的信息需求,都可以考虑使用关系型数据库(摘自 Oracle)。

我们正在建造什么?

MySQL 是最流行的 SQL 数据库之一。本博客将探讨如何将 MySQL 数据库与 Node.js 服务器结合使用。

读完这篇博客,你将能够:

  1. 创建一个 MySQL 数据库
  2. 将数据库连接到 Node.js 服务器
  3. 配置服务器以在数据库中创建(C)、检索(R)、更新(U)和删除(D)数据。
  4. 向客户端发送相应的服务器响应

为了迎接足球赛季,我们将创建一个 CRUD 应用程序来管理梦幻足球的四分卫排名数据!
gif

在我们开始之前……

梦幻足球数据

我们将使用来自FantasyData的四分卫排名数据。

点击链接,并在新标签页中打开。我们稍后会用到它!

背景阅读

安装并设置好 MySQL 数据库后,我们将使用 Express 框架构建一个 Node.js 服务器。

我们将快速略过很多步骤,因为我之前的博客文章中已经对这些步骤进行了详细的解释:

-使用 Express 作为 Node.js 框架构建服务器的入门指南
-构建 Node.js 服务器的入门指南

如果您需要更深入地了解本教程中涵盖的步骤,请随时参考这些博客。

GitHub 仓库

这是我们将要构建的服务器的GitHub 代码库。如果您在学习过程中遇到任何错误,请参考此代码库。

我们开始吧!

安装 MySQL

我们将安装免费版的 MySQL Community Server 和 MySQL Workbench。

Windows 和 macOS 的安装步骤非常相似,只有细微差别。主要区别在于,在 Windows 系统中,您可以一次性下载社区服务器和工作台;而在 macOS 系统中,您需要分别下载它们。

为了尽量保持篇幅简短,我将只介绍 Windows 系统的安装步骤。不过别担心,如果您在安装过程中遇到问题,网上有很多针对 Mac 用户的安装视频教程。

步骤 1:访问 MySQL 主页

访问 mysql.com。点击“下载”选项(绿色方框)。

替代文字

步骤 2:选择 MySQL 社区版(GPL)下载

向下滚动并点击MySQL Community(GPL) 下载选项(绿色方框)。

替代文字

步骤 3:点击 MySQL Community Server(橙色框)

替代文字

提醒:
如果您在 Windows 系统上安装,点击 MySQL Community Server 将为您提供下载社区服务器和工作台的选项。

macOS 用户需要分别下载 MySQL Community Server(橙色框)和 MySQL Workbench(绿色框)。

第四步:选择操作系统并前往下载页面(橙色框)

替代文字

步骤 5:选择第一个下载选项(绿色方框)

替代文字

步骤 6:选择“不用了,直接开始下载”选项(红色方框)

替代文字

步骤 7:点击下载并开始安装过程

MySQL下载完成后,点击下载的文件并按照安装步骤进行操作。同意软件许可协议的条款。

步骤 8:选择底部的“自定义”选项(绿色框),然后单击“下一步”。

替代文字

步骤 9:将 MySQL 服务器和 MySQL Workbench 添加到待安装产品/功能列表中

替代文字

请查看绿色方框标出的区域。

点击左侧的“+”号展开“MySQL 服务器”选项。
然后,展开“MySQL 服务器”和“MySQL 服务器 8.0”。

选择列表顶部的服务器。点击向右的箭头(绿色方框)将 MySQL 服务器添加到“待安装产品/功能”列表中。

完成此步骤后,您应该会看到 MySQL Community Server 已添加到列表中(橙色框)。

返回绿色方框突出显示的区域。展开“应用程序”、“MySQL Workbench”和“MySQL Workbench 8.0”。

在列表顶部选择工作台,然后单击向右的箭头。工作台将被添加到“待安装产品/功能”列表(橙色框)中。

点击“下一步”按钮。

步骤 10:点击“执行”按钮(绿色方框)安装 MySQL Community Server 和 MySQL Workbench。

替代文字

步骤 11:完成配置
此时,应该会弹出一个 MySQL 安装程序窗口,指导您完成配置。

替代文字

选择“独立 MySQL 服务器/经典 MySQL 复制”选项,然后单击“下一步”。

它应该会引导您进入“类型和网络”步骤。保留默认值,然后单击“下一步”。

在身份验证方法步骤中,选择“使用旧版身份验证方法”选项,然后单击“下一步”。

在“帐户和角色”步骤中,输入您要用于访问 MySQL 数据库的密码,将其保存在安全的地方,然后单击“下一步”。

在“Windows 服务”步骤中,选择“将 MySQL 服务器配置为 Windows 服务”选项,然后单击“下一步”。

对于日志记录选项和高级选项,请保留默认设置并单击“下一步”。

在“应用配置”步骤中,单击“执行”。

配置完成后,它应该会自动启动 MySQL 服务器。

注意:
Windows 用户已完成 MySQL Community Server 和 MySQL Workbench 的安装。Mac 用户需要返回下载页面单独安装 Workbench。

设置 MySQL Workbench

Workbench 是我们数据库的可视化客户端。它允许我们在 Node.js 服务器之外检查和探索数据库。在使用 MySQL 数据库时,它将是你最好的帮手,因为它能让调试和开发变得更加轻松!

步骤 1:打开 MySQL 工作台并连接到数据库

你应该会在桌面上看到一个海豚图标。双击即可打开。

替代文字

你应该能看到一个已经在运行的本地实例(红色方框)。

要连接到数据库,请双击本地实例。系统会提示您输入在安装步骤中提供的密码。

您将看到以下显示内容。

替代文字

步骤 2:创建新模式

点击上图中红色方框突出显示的“架构”选项。屏幕上将显示以下内容。

替代文字

前往工作台左上角。在搜索栏下方,右键单击以查看下拉菜单。选择“创建架构”选项(红色框)。

替代文字

将模式命名为 fantasy_football(绿色框)。单击“应用”(红色框)。

系统会提示您检查要应用于数据库的 SQL 脚本。点击“应用”(红色方框)。

替代文字

选中“执行 SQL 语句”(红色框),然后单击“完成”(绿色框)。

替代文字

我们刚刚创建了一个梦幻橄榄球数据库,我们将使用它来创建、检索、更新和删除四分卫排名数据!

步骤 3:创建数据表

让我们创建一个四分卫排名数据表,并输入一位四分卫的信息。

替代文字

在工作台的导航器中,展开 fantasy_football。您会看到一系列选项。右键单击“表格”(绿色框),然后选择“创建表格”选项(红色框)。

替代文字

橙色框内的部分用于指定数据表的名称。绿色框内的部分用于指定列名及其数据类型。

步骤 4:配置数据表

我们将使用来自FantasyData的四分卫排名数据。数据快照如下所示,但请在浏览器中打开该数据,以便更清楚地查看表格。

替代文字

让我们重点关注蓝色高亮显示的列。

我们有四分卫的ID(#)、姓名、位置(pos)、球队和对手球队(opp)。接下来的四列分别展示了三位专家和FantasyData对四分卫的排名。

您可以看到,每一行都显示相应的数据,每一列的数据类型都不同。例如,“名称”列包含字符型数据,“id(#)”列包含整数型数据。

我们将参照 FantasyData 的四分卫排名表来构建我们的数据表。

让我们回到 MySQL 工作台。

下图显示了我们数据表的最终版本。

替代文字

将表名更改为 quarterback_rankings(橙色框)。

请查看绿色方框高亮显示的区域。我们将在这里填写列名及其数据类型。

双击列名下方。现在应该可以在框中输入 ID。按照图片所示,输入 Name、Position、Team、OpposingTeam、JodySmith、EricMoody、JohnFerguson 和 FantasyData 的列名(注意列名采用 PascalCase 格式。单词之间不要有空格,并且首字母大写)。

在“列名称”列的右侧,您会看到“数据类型”列。在“数据类型”列下方,单击空白处。此时会弹出一个下拉菜单,您可以从中选择数据类型。请按照以下说明填写数据类型。

ID、JodySmith、EricMoody、JohnFerguson 和 FantasyData 列包含四分卫的排名编号。请将数据类型指定为 INT(整数)。

列“姓名”、“位置”、“球队”和“对手球队”均包含字符,且所有值均不超过 20 个字符。请选择 VARCHAR(45) 作为它们的数据类型。

另外,VARCHAR 后面的括号允许您指定允许的字符数。如果您的使用场景需要更长的字符,请更改字符数。对于较长的文本行,请选择 Text 作为数据类型。

如果您查看“数据类型”列的右侧,您会看到以缩写形式表示的列属性。我们来逐一了解这些属性。

PK:主键。
主键唯一标识表中的每条记录。它必须包含唯一值,且不能包含空值。一个表只能有一个主键(摘自w3schools.com)。

NN:非空
值不能为空。

UQ:唯一
值必须是唯一的。

B:二进制
值存储任何类型的二进制数据,如图像、word 文件、ext 文件等(摘自tutlane)。

UN:无符号
值不为负数。

ZF:零填充
ZF 将字段的显示值填充为零,直到达到列定义中设置的显示宽度(摘自tutorialspoint)。

AI:auto_increment
AI 允许在向表中插入新记录时自动生成一个唯一编号,并且每插入一条记录,该编号就递增 1(摘自w3schools.com)。

G:生成的列
G 存储数据,但实际上并不通过 SQL 中的 INSERT 或 UPDATE 子句发送数据(摘自gabi.dev)。

ID 用作每位四分卫 (PK) 的唯一标识符。ID 必须是唯一的 (UQ) 值,且不能为空 (NN)。ID 不能为负值 (US)。当向表中插入新记录时,ID 必须自动生成,并且每插入一条记录,ID 值就递增 1 (AI)。

因此,为 ID 列选择的列属性为 PK、NN、UQ、UN 和 AI。

对于其余列,仅选择 NN,因为这些列都不能为空值。

替代文字

点击“申请”(蓝色方框)。

此时会弹出一个窗口,提示您查看要应用于数据库的 SQL 脚本。点击“应用”(橙色框)。

替代文字

此时会弹出另一个窗口。保留默认设置,然后单击“完成”。

第五步:输入一名顶级四分卫的数据

现在你应该能在左侧导航栏看到四分卫排名表(浅蓝色高亮显示)。将鼠标悬停在四分卫排名表上时,应该会出现三个图标。

替代文字

点击最右侧标有红色箭头的图标。工作台应显示以下内容。

替代文字

请查看橙色方框高亮显示的部分。它的列与FantasyData中的数据表相同。太棒了!

让我们来填写帕特里克·马霍姆斯的信息!要填写数据,只需双击每一列下方,然后输入如下所示的来自FantasyData表格的帕特里克·马霍姆斯的数据即可。

替代文字

然后,点击“应用”(绿色方框)。

您会看到一个弹出窗口,提示您查看要应用于数据库的 SQL 脚本。点击“应用”。

此时会弹出另一个窗口。保留默认设置,然后单击“完成”。

好了,我们的 MySQL 数据库准备就绪。

让我们创建一个Node.js服务器来与我们的新数据库进行交互。

使用 Express 框架创建 Node.js 服务器

步骤 1:为我们的服务器创建一个目录

在相应的目录中,在终端中输入以下命令。

#in terminal
mkdir Fantasy_Football
Enter fullscreen mode Exit fullscreen mode

进入 Fantasy_Football 目录,并用文本编辑器打开它。

#in terminal
cd Fantasy_Football
code .
Enter fullscreen mode Exit fullscreen mode

步骤 2:创建 package.json 文件

package.json 文件记录了它所依赖的所有软件包和应用程序、其独特的源代码控制信息以及特定的元数据,例如项目的名称、描述和作者(摘自nodesource.com)。

在终端中输入:

#in terminal
npm init
Enter fullscreen mode Exit fullscreen mode

接下来,系统会向您展示一系列关于您应用程序详细信息的问题,每回答完一个问题,按下回车键即可。

您可以自行选择填写这些信息,但为了本教程的目的,我们可以跳过这部分。多次按回车键,直到终端退出问卷调查。

此时,您应该可以看到已经为您创建了 package.json 文件。

步骤 3:安装必要的软件包和工具

安装 mysql、express 和 body-parser 作为生产环境依赖项。在终端中运行以下命令。

#in terminal
npm i --save express mysql body-parser
Enter fullscreen mode Exit fullscreen mode

在终端中运行以下命令,将 nodemon 安装为开发依赖项。

#in terminal
npm i --save-dev nodemon
Enter fullscreen mode Exit fullscreen mode

打开你的 package.json 文件。

替代文字

你会看到 body-parser、express 和 mysql 已作为生产依赖项安装(绿色框),而 nodemon 已作为开发依赖项安装(黄色框)。

接下来,让我们指示我们的应用程序使用 nodemon 在每次代码发生更改时重新启动我们的应用程序。

在红色方框突出显示的部分,在第 7 行末尾添加逗号。在第 8 行,添加启动脚本“start”:“nodemon server.js”,如上图所示。

在资源管理器中,您还应该看到已为您创建了 package-lock.json 文件(蓝色框)。

步骤 4:创建一个名为 utils 的文件夹。在该文件夹内创建一个名为 dabase.js 的文件。

您的目录结构应如下所示。

替代文字

步骤 5:创建 routes 文件夹。在该文件夹中创建一个名为 qb.js 的文件。

您的目录结构应如下所示。

替代文字

qb 是 quarterback(四分卫)的缩写。我们将在这里编写 SQL 查询语句,将四分卫排名数据存储到我们的数据库中。

将以下代码复制并粘贴到 qb.js 中。

#in routes>qb.js
const express = require("express");
const mysqlConnection = require("../utils/database");

const Router = express.Router();

Router.get("/", (req, res) => {

});

module.exports = Router;
Enter fullscreen mode Exit fullscreen mode

暂时不用担心代码。我们稍后会逐行讲解!

步骤 6:创建 server.js 文件并配置服务器

在终端中执行以下命令。

#in terminal
touch server.js 
Enter fullscreen mode Exit fullscreen mode

你会看到目录中已创建了 server.js 文件。

在 server.js 文件中,复制并粘贴以下代码。

#in server.js
const mysql = require("mysql");
const express = require("express");
const bodyParser = require("body-parser");
const qbRoutes = require("./routes/qb");

const app = express();

app.use(bodyParser.json());

app.use(qbRoutes);

app.listen(4000);
Enter fullscreen mode Exit fullscreen mode

我们一行一行地来分析这段代码。为了更清晰地解释代码,我可能会稍微跳过一些部分,所以请务必注意行号。

替代文字

第 1-3 行:
在安装过程中,我们安装了三个包(mysql、express 和 bodyParser)。我们需要将这些包导入到 server.js 中,才能使用这些包提供的所有强大功能。

第 6 行
这些功能中,express() 用于创建 Express 应用。将 express() 的值设置为一个常量 app。

第 12 行
app.listen(4000) 创建一个监听 4000 端口的服务器。

第 8 行
当向服务器发送 HTTP 请求时,数据包含在请求体中。在处理数据之前,我们需要先使用 bodyParser 解析数据。

第 8 行允许您在服务器中使用 bodyParser。

替代文字

第 10 行
当你在 Express 应用中看到 app.use() 时,要知道你正在查看的是一个中间件函数。

在我之前关于Express的博客文章中,我们深入探讨了中间件。如果您在学习本教程的过程中对这个概念感到困惑,请参考那篇博客文章,以便更深入地理解我们将要编写的代码。

简而言之,中间件函数旨在识别特定类型的 HTTP 请求(GET、POST、PUT、DELETE)及其 URL。当中间件函数识别到匹配的请求时,其自身函数将被触发,并向浏览器发送相应的响应。

在服务器端详细编写中间件函数可能会导致 server.js 文件过长且难以阅读。

在设置过程中,我们创建了一个名为 routes 的文件夹,并在其中创建了一个 qb.js 文件。

为了将代码分隔开来,我们将在 qb.js 中编写中间件函数的详细信息,并将其作为参数传递到第 10 行的 app.use() 中。

替代文字

第 4 行
为了传递第 10 行中用 qb.js 编写的中间件函数,我们需要导入 qb.js 文件(第 4 行)。

步骤 7:将 MySQL 数据库连接到 Node.js 服务器

找到 utils 文件夹,并打开其中的 database.js 文件。我们将在这里把数据库连接到服务器。

复制以下代码并粘贴到 database.js 文件中。

#in utils>dabase.js
const mysql = require("mysql");

const mysqlConnection = mysql.createConnection({
  host: "localhost",
  user: "root",
  database: "fantasy_football",
  password: "ENTER YOUR MYSQL DB PASSWORD HERE",
  multipleStatements: true,
});

mysqlConnection.connect((err) => {
  if (!err) {
    console.log("Connected");
  } else {
    console.log("Connection Failed");
  }
});

module.exports = mysqlConnection;

Enter fullscreen mode Exit fullscreen mode

让我们逐行分析!

替代文字

第 1 行:
在设置过程中,我们已在服务器上安装了 MySQL。将其导入到 database.js 文件中。这将使我们能够访问所有方法,从而将 Node.js 服务器连接到 fantasy_football 数据库。

第 3-9 行
首先,我们需要在 MySQL 数据库和服务器之间建立连接。我们可以通过调用 `createConnection()` 方法来实现。在这个方法中,我们需要提供有关我们要连接到 Node.js 服务器的数据库的信息。我们将其设置为常量 `mysqlConnection`。

替代文字

第 4 行
数据库主机名将是 localhost,因为我们是在本地机器上运行的。

第 5 行
我们将用户名定义为“root”,因为它是在配置过程中分配给我们的。

第 6 行
对于数据库名称,我们将输入 fantasy_football,因为这是我们给数据库起的名字。

第 7 行
:密码,请输入您创建数据库时使用的密码。

第 8 行
对于 multipleStatements,添加值为 true,因为我们将在 qb.js 中执行多个语句查询。

替代文字

第 11-19 行:
现在我们已经创建了连接,接下来将使用 connect() 方法将数据库连接到服务器。此方法接受一个回调函数,该函数以 error 为参数。如果服务器连接数据库失败,则会抛出此错误。

为了方便地检查数据库连接,我们编写了一个错误处理程序。第 12-18 行的代码表示,如果没有错误,则在服务器控制台中打印“已连接”;如果有错误,则打印“连接失败”。

第 21 行
我们导出 mysqlConnection,因为我们将在 qb.js 文件中使用它!

让我们检查一下数据库是否已连接到 Node.js 服务器。

在终端中运行以下命令。

#in terminal
npm start
Enter fullscreen mode Exit fullscreen mode

服务器应该已连接到数据库,并且您应该在控制台上看到以下消息。

替代文字

步骤 8:配置 qb.js 以处理 GET 请求

找到 routes 文件夹并打开 qb.js 文件。

我们将在 qb.js 文件中编写中间件函数的具体细节。如前所述,HTTP 请求(GET、POST、PUT、DELETE)会依次经过多个中间件函数,直到找到能够处理该请求的函数。

当中间件函数识别到匹配的请求时,它会向 MySQL 数据库发送查询,以创建、检索、更新或删除数据。操作完成后,服务器会向浏览器发送相应的响应。

将 qb.js 中的现有代码替换为以下代码。

#in routes>qb.js
const express = require("express");
const mysqlConnection = require("../utils/database");

const Router = express.Router();

Router.get("/", (req, res) => {
  mysqlConnection.query(
    "SELECT * FROM quarterback_rankings",
    (err, results, fields) => {
      if (!err) {
        res.send(results);
      } else {
        console.log(err);
      }
    }
  );
});

Router.post("/", (req, res) => {
  let qb = req.body;
  const sql =
    "SET @ID = ?;SET @Name = ?;SET @Position = ?;SET @Team = ?;SET @OpposingTeam = ?;SET @JodySmith = ?;SET @EricMoody = ?;SET @JohnFerguson = ?;SET @FantasyData = ?; CALL Add_or_Update_QB(@ID, @Name, @Position, @Team, @OpposingTeam, @JodySmith, @EricMoody, @JohnFerguson, @FantasyData);";
  mysqlConnection.query(
    sql,
    [
      qb.ID,
      qb.Name,
      qb.Position,
      qb.Team,
      qb.OpposingTeam,
      qb.JodySmith,
      qb.EricMoody,
      qb.JohnFerguson,
      qb.FantasyData,
    ],
    (err, results, fields) => {
      if (!err) {
        results.forEach((element) => {
          if (element.constructor == Array) res.send(element);
        });
      } else {
        console.log(err);
      }
    }
  );
});

Router.put("/", (req, res) => {
  let qb = req.body;
  const sql =
    "SET @ID = ?;SET @Name = ?;SET @Position = ?;SET @Team = ?;SET @OpposingTeam = ?;SET @JodySmith = ?;SET @EricMoody = ?;SET @JohnFerguson = ?;SET @FantasyData = ?; CALL Add_or_Update_QB(@ID, @Name, @Position, @Team, @OpposingTeam, @JodySmith, @EricMoody, @JohnFerguson, @FantasyData);";
  mysqlConnection.query(
    sql,
    [
      qb.ID,
      qb.Name,
      qb.Position,
      qb.Team,
      qb.OpposingTeam,
      qb.JodySmith,
      qb.EricMoody,
      qb.JohnFerguson,
      qb.FantasyData,
    ],
    (err, results, fields) => {
      if (!err) {
        res.send(
          "The data for the selected quarterback has been successfully updated."
        );
      } else {
        console.log(err);
      }
    }
  );
});

Router.delete("/:id", (req, res) => {
  mysqlConnection.query(
    "DELETE FROM quarterback_rankings WHERE ID= ? ",
    [req.params.id],
    (err, results, fields) => {
      if (!err) {
        res.send("The selected quarterback has been successfully deleted.");
      } else {
        console.log(err);
      }
    }
  );
});

module.exports = Router;
Enter fullscreen mode Exit fullscreen mode

让我们逐行分析!

替代文字

第 1 行
我们导入 Express 以访问其 Router() 方法。

第 2 行
我们导入 mysqlConnection,因为我们需要它向数据库发送查询。

第 4 行
我们在这里调用 Router() 方法,以创建处理不同 HTTP 请求的路由器级中间件函数。

第 6-14 行:
这是编写处理来自浏览器的 GET 请求的路由器级中间件函数的方法。

中间件函数的语法和路由级中间件函数的概念我已经在我之前关于Express的博客中介绍过了。所以我们直接跳到对数据库执行的 SQL 查询。

替代文字

第 7 行,
我们通过调用 mysqlConnection 的 query 方法向数据库发送查询。在括号内,我们编写一个 SQL 查询(“SELECT * FROM quarterback_rankings”)和一个回调函数,该函数包含最终错误、结果和字段。

让我们来分析一下。

SQL 查询允许我们与数据库进行通信。通过我们的 Node.js 服务器,我们可以指示数据库创建、检索、更新或删除数据。

SELECT 语句允许我们从数据库中选择要提取的特定信息。在 SELECT 语句后添加 * 号,告诉数据库我们要从之前创建的 quarterback_rankings 表中提取所有信息。

替代文字

目前我们只有关于帕特里克·马霍姆斯的一条信息。所以我们应该获取到关于帕特里克·马霍姆斯的一条信息。

在执行 SQL 查询之后,我们编写一个回调函数,其中包含最终错误、结果和字段。

替代文字

第 9-12 行的意思是,如果在 SQL 数据库运行查询时没有遇到错误,则将结果作为响应发送;如果出现错误,则在控制台中打印错误信息。

好的!我们来测试一下。

您之前已经下载了Postman。我们将使用它来测试从我们的服务器发送的查询是否能被MySQL数据库正确处理。

我在之前的博客中已经介绍了 Postman 的总体布局以及如何使用它,所以我们将快速浏览这部分内容。

如果需要更多解释,请查看我之前的博客:

  1. 强参数和验证入门指南
  2. API 测试编写入门指南

打开Postman。

替代文字

Select the HTTP method to GET(red box). Enter the url localhost:4000 in the url bar(orange box) and press send(blue button).

Take a look at the body region highlighted with a green box. You will see that info regarding Patrick Mahomes has been retrieved for you. Woot woot!

Step 9: Configure qb.js to handle POST request
Our server and database should be able to handle POST and PUT requests.

To create or update a record in our table, we need to send the values for all the columns in our data table(id, name, position, team & etc). As you can imagine, the SQL queries for these requests could get quite lengthy!

Instead of writing this out for both POST and PUT requests in our qb.js file, we will write it out once in MySQL Server and save it as a stored procedure. Then, we will call the stored procedure in qb.js to execute it.

Go to MySQL Workbench. In your navigator, locate fantasy_football database. Expand it to locate Stored Procedures option(green box).

替代文字

Right click on Store Procedures to display a drop down menu. Select Create Stored procedure(orange box).

In the region highlighted with a blue box, we will write out the procedure.

The code enclosed within a blue box is the basic syntax of create procedure statement. In line 1, you can replace _new_procedure with the name of your stored procedure. When you specify the name, it should automatically display the name in the region highlighted with a yellow box.

( ) is a space for you to specify a list of comma-separated parameters for the stored procedure.

Between the Begin and End block, you can write the code that instructs the database to either create or update a record in quarterback_rankings data table.

Copy and paste the following into the region highlighted with a blue box.

CREATE DEFINER=`root`@`localhost` PROCEDURE `Add_or_Update_QB`(
IN _ID INT, 
IN _Name varchar(45),
IN _Position varchar(45),
IN _Team varchar(45),
IN _OpposingTeam varchar(45),
IN _JodySmith INT,
IN _EricMoody INT,
IN _JohnFerguson INT,
IN _FantasyData INT
)
BEGIN
    IF _ID = 0 THEN
        INSERT INTO quarterback_rankings(Name, Position, Team, OpposingTeam, JodySmith, EricMoody, JohnFerguson, FantasyData)
        VALUES (_Name,_Position,_Team,_OpposingTeam,_JodySmith,_EricMoody,_JohnFerguson,_FantasyData );

        SET _ID = LAST_INSERT_ID();
    ELSE
        UPDATE quarterback_rankings
        SET
        Name = _Name,
        Position = _Position,
        Team = _Team, 
        OpposingTeam = _OpposingTeam, 
        JodySmith = _JodySmith,
        EricMoody = _EricMoody,
        JohnFerguson = _JohnFerguson,
        FantasyData = _FantasyData
        WHERE ID = _ID;
    END IF;
    SELECT * FROM quarterback_rankings;
END
Enter fullscreen mode Exit fullscreen mode

Click on Apply. You will see a pop up window nudging you to review the SQL script to be applied on the database. Click on Apply.

Another window should pop up. Leave the default setting and click onFinish.

Let's go over these line by line!

替代文字

Line 1
This line allows you to create a procedure. We have specified the name of the procedure to be Add_or_Update_QB.

Lines 2-10
In MySQL, there are three modes of parameters: IN, OUT, or INOUT.

IN is the default mode and when you define an IN parameter in a stored procedure, the calling program(i.e. our server) has to pass an argument to the stored procedure(excerpt from mysqltutorial.org).

I am sure this sounds very abstract at the moment. Let's look at the big picture and see where these IN parameters come in to play.

When the server receives a POST request from the browser, it receives the values for all the columns in our data table(id, name, position, team & etc) in the body of the request. The server parses the data and sends these parameters to the database in a query. These parameters are the IN parameters you are looking at now!

Let's write this out.

替代文字

First, you need to specify the parameter mode IN. Then, specify the name of the parameter. These must be identical to the column names in the data table you are making changes to(i.e. quarterback_rankings).

替代文字

Then, you must specify its data type. If the data type is varchar, you must specify the maximum length of the parameter.

Lines 12-32
替代文字
Between the Begin and End block, you can write conditional statements on how you would like the database to create or update a record in our data table.

We will be writing a IF-THEN-ELSE statement and its syntax looks like the following.

IF condition THEN
   statements;
ELSE
   else-statements;
END IF;
Enter fullscreen mode Exit fullscreen mode

If condition is true, then we execute the statement in between IF -THEN and ELSE. If condition is not true, then the else-statement between ELSE and END IF will execute.

替代文字

Lines 13-17
When our server receives the POST request, it will send the parameters(_ID, _Name, _Position, _Team, _OpposingTeam, _JodySmith, _EricMoody, _JohnFerguson, _FantasyData).

These lines are saying that if the _ID in the query is 0, then INSERT the parameters(_ID, _Name, _Position, _Team, _OpposingTeam, _JodySmith, _EricMoody, _JohnFerguson, _FantasyData) as values for columns(Name, Position, Team, OpposingTeam, JodySmith, EricMoody, JohnFerguson, FantasyData) in the quarterback_rankings table.

This essentially creates a new record in the table.

Then, set the _ID of the new record as auto_increment id of the last row that has been inserted or updated in a table(line 17).

替代文字

Lines 18-30
If _ID parameter in the query is not 0(line 18), then find the row whose ID matches the _ID of the parameter(line 29). Then, update that row(line 19) by setting the values of the specified columns with the corresponding parameters in the query(lines 21-28).

Line 31
Retrieve everything from quarterback-rankings table and send it to the server.

Time to return to qb.js in our server!

替代文字

Line 19
We create a router-level middleware function for a POST request.

Line 21-22
We invoke our stored procedure Add_or_Update_QB by using the CALL statement(red box). Remember the IN parameters we have written in our stored procedure? Our server has to pass these parameters to the stored procedure by including them in the parenthesis.

In line 21, we create a constant called sql. In line 22, we create variables for all of the parameters we are passing through Add_or_Update_QB and setting it equal to ?. The ?s, AKA the values of these variables will be dynamically retrieved from the body of the POST request.

Then, we invoke Add_or_Update_QB stored procedure and pass these variables as parameters(red box).

Lines 23-35
We create a SQL query(line 23) that we will send to the database. In the query, we pass the variable sql. Remember how we set the variables in line 22 to question marks?

In line 20, we grab the body of the request that contains all of these values and set it equal to qb.

In lines 26-34, we grab these values and replace the ? of corresponding variables.

替代文字

Lines 36-43
These lines of code are very similar to the call back function of our GET request. This functions contains eventual error, results, and fields.

We are saying that if no error is encountered while running queries in SQL database, then send the array element that contains all the info retrieved from the database and send it to the browser. If there is an error, then print the error in the console.

A little background information on lines 38-39. The results that come back from the database is an array that contains a mix of objects and an array that contains info about the record we have created. So we are simply iterating through the elements of the results array(results.forEach((element)). If we come across an element that is an array(if (element.constructor === Array) res.send(element)), then we are sending that element as a response.

All right! Let's test to see if this works.

Open up Postman.

替代文字

Change the HTTP method to POST(red box).

Under the url bar, click on Body tab(grey box). It should present multiple options below.

Select raw(orange box). If you look to the right you will see the Text option. Click on it to access the drop down menu and select JSON(yellow box).

In the region below raw and JSON tabs(purple box), copy and paste the following.

    {
        "ID": 0,
        "Name": "Lamar Jackson",
        "Position": "QB",
        "Team": "BAL",
        "OpposingTeam": "vs. CLE",
        "JodySmith": 4,
        "EricMoody": 1,
        "JohnFerguson": 1,
        "FantasyData": 2
    }
Enter fullscreen mode Exit fullscreen mode

This is the JavaScript object that contains all the parameters necessary to create a record in our quarterback_rankings table in MySQL database. Notice that the ID set to 0.

Let's see how everything comes together.

When the browser sends this POST request, our server receives the the sent info in the body of the request.

替代文字

The server parses the data and sends these parameters to the database in a query. The query invokes the stored procedure which takes in these parameters(IN parameters).

替代文字

Our stored procedure recognizes that ID parameter is 0 and inserts the values of these parameters to the appropriate columns in our quarterback_rankings table.

替代文字

All coming together now, right?

Now, press Send in Postman!

替代文字

If you look at the response, you will see that a new record of Lamar Jackson has been created(blue box).

Don't mind the "ID" of 10 you see on my image. I have been playing around with this database for a while and have created and deleted multiple records. If you are doing this for the first time around, Lamar Jackson should have an ID of 2.

Let's go back to MySQL database.

替代文字

请确保屏幕上已打开四分卫排名表。点击闪电图标刷新表格(红色方框)。

你会看到拉马尔·杰克逊创造了一项新纪录(蓝色方框)!

步骤 10:配置 qb.js 以处理 PUT 请求
更新数据库记录的代码与 POST 请求几乎相同。

图中用红色方框标出了两处不同之处。

第 48 行,我们指定 HTTP 方法为 PUT。第 67 行,我们发送一条消息,表明记录已成功更新。

替代文字

让我们用 Postman 测试一下!

替代文字

将HTTP方法更改为PUT(红色方框)。

请在请求正文中指定要更改的记录的 ID。例如,我知道我有一条 ID 为 10 的记录(橙色框)。

将对手球队更改为“vs. HOU”(黄色框)。

按下发送键。

查看服务器的响应时,你会看到如下消息:“所选四分卫的数据已成功更新”。

返回 MySQL 数据库。

替代文字

点击闪电图标刷新表格(橙色框)。

您会看到您指定的记录的对手球队已更新为“vs. HOU”(红色方框)!

步骤 11:配置 qb.js 处理 DELETE 请求
DELETE 请求的代码与我们之前编写的 GET 请求非常相似。

替代文字

不同之处用彩色方框突出显示。

第 75 行
HTTP 方法为 delete(红色方框)。

请求的 URL 包含我们要删除的记录的 ID(蓝色框)。

第 77-78 行
SQL 查询指示数据库删除 ID 与请求中的 id 参数匹配的记录。

第 80-81 行
如果没有错误,服务器将发送消息“所选四分卫已成功删除”作为响应。

第 89 行
导出路由器,以便第 10 行的 server.js 可以访问这些路由器级别的中间件函数。

我们来测试一下!

替代文字

在 Postman 中,将 HTTP 方法更改为 DELETE(红色框)。在地址栏中,在 localhost:4000 的末尾添加要删除的记录的/id (橙色框 - localhost:4000/10)。

点击发送。

你会看到服务器发送的消息是“所选四分卫已成功删除。”作为响应。

检查您的 MySQL 数据库,然后点击闪电图标。您会看到,您指定的 ID 对应的记录已从数据表中删除。

替代文字

好了!你现在知道如何操作了:

  1. 创建一个 MySQL 数据库
  2. 将数据库连接到 Node.js 服务器
  3. 配置服务器以创建、检索、更新和删除数据库中的数据。
  4. 向浏览器发送相应的服务器响应

你真是太棒了!现在离开电脑,好好享受你的一天吧!

giphy

文章来源:https://dev.to/lisahjung/beginner-s-guide-to-using-mysql-database-in-a-node-js-app-49li