庹三姐 發表於 2022-9-16 08:55:00

Node.js学习笔记(四)——NodeJS访问MongoDB与MySQL数据库

<div style="font-size: 20px; font-family: microsoft yahei">
<h1>一、MongoDB</h1>
<p>MongoDB是开源,高性能的NoSQL数据库;支持索引、集群、复制和故障转移、各种语言的驱动程序丰富;高伸缩性;<br>MongoDB 是一个基于分布式文件存储的数据库。由 C++ 语言编写。旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。<br>MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。</p>
<p>官网地址:http://www.mongodb.org/</p>
<p>github:https://github.com/mongodb/</p>
<p>API Docs:https://www.mongodb.com/docs/</p>
<p>nodejs驱动:https://github.com/mongodb/node-mongodb-native</p>
<p>文档:https://www.mongodb.com/zh-cn/docs/manual/</p>
<h2>1.1、安装MongoDB</h2>
<p>下载地址:https://www.mongodb.com/try/download/community</p>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220915111345440-2133656392.png" alt="" loading="lazy"></p>
<p>下载成功后点击msi文件直接安装,这里以win7_64位的操作系统为例。</p>
<h3>1.1.1、配置运行环境</h3>
<p><span style="color: rgba(255, 0, 0, 1)"><strong>新版本的MongoDB不需要复杂的配置,不需要单独安装客户端,安装完成后在桌面会找到客户端:</strong></span></p>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220915113141837-413845240.png" alt="" loading="lazy"></p>
<p>&nbsp;点击连接即可登录成功。</p>
<p><strong>1)、创建存放数据的文件夹</strong></p>
<p>在任意没有中文的目录下新建文件夹,如c:\data,在文件夹下存放MongoDB数据库文件与日志文件,如:</p>
<p>c:\data\db用于存放mongodb的数据文件</p>
<p>c:\data\log用于存放mongodb的日志文件</p>
<p><strong>2)、创建配置文件</strong></p>
<p>打开MongoDB的安装目录如“C:\Program Files\MongoDB\Server\3.4\bin”,并在此目录下新建一个mongo.config文件,文件内容如下:</p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 0, 0, 1)">##数据库目录##
dbpath</span>=<span style="color: rgba(0, 0, 0, 1)">C:\data\db

##日志输出文件##
logpath</span>=C:\data\log\db.log</pre>
</div>
<p><strong>3) 、安装Windows服务</strong></p>
<p>安装时添加服务:</p>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220915112121639-505023753.png" alt="" loading="lazy"></p>
<p>使用cmd进入命令行</p>
<p>使用cd切换目录到安装目录下,如:cd &nbsp;C:\Program Files\MongoDB\Server\3.4\bin</p>
<p>安装MongoDB服务且指定配置文件,如:</p>
<p>mongod --config "C:\Program Files\MongoDB\Server\3.4\bin\mongo.config" --install</p>
<p><strong>4)、错误处理</strong></p>
<p>如果运行过程中提示“<span style="color: rgba(255, 0, 0, 1)">无法定位程序输入点ucrtbase.terminate于动态链接库api-ms-win-crt-runtime-|1-1-0.dll</span>”错误,请下载安装“vc_redist.x64”,如果vc redis.x64安装失败请先下载补丁(KB2999226)再安装。</p>
<p>5)、<strong>添加环境变量</strong><br>在计算机-&gt;右键-&gt;高级-&gt;在环境变量PATH中加入"C:\Program Files\MongoDB\Server\3.4\bin"路径。</p>
<p><img src="https://images2015.cnblogs.com/blog/63651/201612/63651-20161223135913729-1912072794.png" alt=""></p>
<p><strong>6)、启动服务</strong><br>在cmd窗口中运行如下命令开始服务,也可以在可以在“控制面板\所有控制面板项\管理工具\服务”手动开启,注意默认是开机就自动启动服务的,可以设置成手动启动。</p>
<p><img src="https://images2015.cnblogs.com/blog/63651/201612/63651-20161223140313932-1919444716.png" alt=""></p>
<p>net start mongodb</p>
<p>停止服务</p>
<p>net stop mongodb</p>
<p>在cmd中运行如下命令</p>
<p><img src="https://images2015.cnblogs.com/blog/63651/201612/63651-20161223140514901-1813768129.png" alt=""></p>
<p>这样安装就成功了!</p>
<h3>1.1.2、运行MongoDB</h3>
<p><strong>1)、直接运行</strong></p>
<p>如果安装完成后不想做任何配置,可以直接运行,其中mongod.exe是服务,应该先启动,如:</p>
<p><strong><img src="https://images2015.cnblogs.com/blog/63651/201612/63651-20161223142606386-13917145.png" alt=""></strong></p>
<p>启动客户端mongo.exe文件,如:</p>
<p><img src="https://images2015.cnblogs.com/blog/63651/201612/63651-20161223142658339-392177038.png" alt=""></p>
<p><strong>2)、启动服务后运行</strong></p>
<p>使用net start mongodb或手动启动服务器运行客户端mongo.exe文件。</p>
<p><strong>3)、可视化工具</strong></p>
<p>当服务启动成功后,如果认为命令行操作不方便,可以使用robomongo等GUI工具。</p>
<p>官网:https://robomongo.org/</p>
<p><img src="https://images2015.cnblogs.com/blog/63651/201612/63651-20161223143034901-1710922317.png" alt=""></p>
<p>&nbsp;第二项是一个绿色版的,解压后在文件夹中找到exe文件直接运行即可。</p>
<p><img src="https://images2015.cnblogs.com/blog/63651/201612/63651-20161223144729307-73341438.png" alt=""></p>
<h2>1.2、数据库操作</h2>
<h3>1.2.1、创建数据库与查看数据库</h3>
<p>以下实例我们创建了数据库gomall</p>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220915113352963-773399259.png" alt="" loading="lazy"></p>
<p>启动shell:</p>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220915120458393-869352838.png" alt="" loading="lazy"></p>
<p>use&nbsp;数据库名,<span style="color: rgba(255, 0, 0, 1)">如果数据库不存在则创建</span>,使用show dbs可查看所有数据库</p>
<p>&gt; use&nbsp;gomall&nbsp;&nbsp;<br>switched to db&nbsp;gomall<br>&gt; db<br>gomall</p>
<p>&gt;db.gomall.insertOne({name:"gomall"});</p>
<p>如果使用GUI工具在连接名称上右键create database也可以创建数据库:</p>
<p><img src="https://images2015.cnblogs.com/blog/63651/201612/63651-20161223145117698-2022423470.png" alt=""></p>
<p>&nbsp;创建成功后如下所示:</p>
<p><img src="https://images2015.cnblogs.com/blog/63651/201612/63651-20161223145151542-639264237.png" alt=""></p>
<p>Collections表示集合,类似关系数据库中的表。</p>
<p>Functions表示函数,类似关系数据库中的存储过程与函数。</p>
<p>Users表示用户。</p>
<p>document表示记录,类似关系数据为中的记录或行。</p>
<p>如果你想查看所有数据库,可以使用 show dbs 命令:<br>&gt; show dbs</p>
<p>MongoDB 中默认的数据库为 test,如果你没有创建新的数据库,集合将存放在 test 数据库中。</p>
<p><img src="https://images2015.cnblogs.com/blog/63651/201612/63651-20161223145435276-514677717.png" alt=""></p>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220915113541978-1047521.png" alt="" loading="lazy"></p>
<p>创建集合</p>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220915113637388-419824623.png" alt="" loading="lazy"></p>
<p>使用命令行创建:</p>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220916104405770-12934492.png" alt="" loading="lazy"></p>
<h3>1.2.2、删除数据库</h3>
<p>&gt; use&nbsp;gomall<br>switched to db gomall<br>&gt; db.dropDatabase()<br>{ "dropped" : "gomall", "ok" : 1 }</p>
<p><img src="https://images2015.cnblogs.com/blog/63651/201612/63651-20161223145642948-166498178.png" alt=""></p>
<h3>1.2.3、插入数据</h3>
<p><strong>a)、db.集合.insertOne(数据)</strong></p>
<p>这里的数据可以是JSON</p>
<p>先打开shell脚本编写的界面,操作如下:</p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 0, 0, 1)">db.movies.insertOne(
{
    title: </span>"The Favourite"<span style="color: rgba(0, 0, 0, 1)">,
    genres: [ </span>"Drama", "History"<span style="color: rgba(0, 0, 0, 1)"> ],
    runtime: </span>121<span style="color: rgba(0, 0, 0, 1)">,
    rated: </span>"R"<span style="color: rgba(0, 0, 0, 1)">,
    year: </span>2018<span style="color: rgba(0, 0, 0, 1)">,
    directors: [ </span>"Yorgos Lanthimos"<span style="color: rgba(0, 0, 0, 1)"> ],
    cast: [ </span>"Olivia Colman", "Emma Stone", "Rachel Weisz"<span style="color: rgba(0, 0, 0, 1)"> ],
    type: </span>"movie"<span style="color: rgba(0, 0, 0, 1)">
}
)</span></pre>
</div>
<p>db.products.insertOne({name:"iphone",price:1988});</p>
<p>从上图操作可以看出,没有去创建“products”集合,其实通过插入操作也会自动创建<br>_id,是mongodb自已生成的,每行数据都会存在,默认是ObjectId,可以在插入数据时插入这个键的值(支持mongodb支持的所有数据类型) </p>
<p>查看数据:db.products.find({})</p>
<p><strong>b)、db.表名.insertMany(数据);</strong></p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 0, 0, 1)">use sample_mflix
db.movies.insertMany([
   {
      title: </span>"Jurassic World: Fallen Kingdom"<span style="color: rgba(0, 0, 0, 1)">,
      genres: [ </span>"Action", "Sci-Fi"<span style="color: rgba(0, 0, 0, 1)"> ],
      runtime: </span>130<span style="color: rgba(0, 0, 0, 1)">,
      rated: </span>"PG-13"<span style="color: rgba(0, 0, 0, 1)">,
      year: </span>2018<span style="color: rgba(0, 0, 0, 1)">,
      directors: [ </span>"J. A. Bayona"<span style="color: rgba(0, 0, 0, 1)"> ],
      cast: [ </span>"Chris Pratt", "Bryce Dallas Howard", "Rafe Spall"<span style="color: rgba(0, 0, 0, 1)"> ],
      type: </span>"movie"<span style="color: rgba(0, 0, 0, 1)">
    },
    {
      title: </span>"Tag"<span style="color: rgba(0, 0, 0, 1)">,
      genres: [ </span>"Comedy", "Action"<span style="color: rgba(0, 0, 0, 1)"> ],
      runtime: </span>105<span style="color: rgba(0, 0, 0, 1)">,
      rated: </span>"R"<span style="color: rgba(0, 0, 0, 1)">,
      year: </span>2018<span style="color: rgba(0, 0, 0, 1)">,
      directors: [ </span>"Jeff Tomsic"<span style="color: rgba(0, 0, 0, 1)"> ],
      cast: [ </span>"Annabelle Wallis", "Jeremy Renner", "Jon Hamm"<span style="color: rgba(0, 0, 0, 1)"> ],
      type: </span>"movie"<span style="color: rgba(0, 0, 0, 1)">
    }
])</span></pre>
</div>
<p>_id可以自已插入、一个表中不一定要字段都相同,虽然insert和save方法都可以插入数据,当默认的“_id”值已存在时,调用insert方法插入会报错;而save方法不会,会更新相同的_id所在行数据的信息。</p>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220916105230089-1293722590.png" alt="" loading="lazy"></p>
<h3>1.2.4、查询数据</h3>
<p>a)、查询集合中所有数据:db.集合.find();</p>
<p>db.students.find({name:"tom"});&nbsp; 查找name属性为tom的数据(document)</p>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220916105553481-601259747.png" alt="" loading="lazy"></p>
<p>无条件时查找所有如:</p>
<p>db.students.find()</p>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220916105450719-123193584.png" alt="" loading="lazy"></p>
<p>b)、按条件查询(支持多条件):db.集合.find(条件);</p>
<p>db.students.find({name:"tom",age:19});</p>
<p>对象中的条件要求同时成立</p>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220916105714755-1054048636.png" alt="" loading="lazy"></p>
<p>c)、查询第一条(支持条件):db.集合.findOne(条件);</p>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220916110040118-942933301.png" alt="" loading="lazy"></p>
<p>d)、限制数量:db.集合.find().limit(数量);</p>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220916110331252-933167568.png" alt="" loading="lazy"></p>
<p>e)、跳过指定数量:db.表名.find().skip(数量);</p>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220916110427315-1080200210.png" alt="" loading="lazy"></p>
<p>f)、比较查询<br>大于:﹩gt<br>小于:<span style="font-size: 18pt">﹩</span>lt<br>大于等于:﹩gte<br>小于等于:﹩lte<br>非等于:﹩ne</p>
<p>db.users.find({age:{'﹩gt':9}});</p>
<p>查找年龄大于9且小于11岁的</p>
<p>db.users.find({age:{'﹩gt':9,'﹩lt':11}});</p>
<p>查询年龄大于17岁的学生:</p>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220916105954885-2022538617.png" alt="" loading="lazy"></p>
<p>g)、查询数量:db.表名.find().count();</p>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220916110503719-1645898757.png" alt="" loading="lazy"></p>
<p>h)、排序:db.表名.find().sort({"字段名":1});</p>
<p>1:表示升序,-1:表示降序</p>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220916110554334-1428848775.png" alt="" loading="lazy"></p>
<p>i)、指定字段返回: db.表名.find({},{"字段名":0}); &nbsp;参数1:返回 0:不返回</p>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220916110654456-1974699310.png" alt="" loading="lazy"></p>
<p>更多:https://www.mongodb.com/docs/mongodb-shell/crud/read/#std-label-mongosh-read</p>
<h3>1.2.5、修改</h3>
<p>前面save在_id字段已存在是就是修改操作,按指定条件修改语法如下:</p>
<p>db.集合.update({"条件字段名":"字段值"},{﹩set:{"要修改的字段名":"修改后的字段值"}});</p>
<p>db.users.updateOne({age:{'﹩eq':9}},{﹩set:{age:100}});</p>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220916145007728-672136900.png" alt="" loading="lazy"></p>
<p>修改多条:</p>
<p>db.users.updateMany({age:{"﹩gte":10}},{﹩set:{age:30}});</p>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220916145844196-1213190208.png" alt="" loading="lazy"><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220916150512201-449618779.png" alt="" loading="lazy"></p>
<p>更多</p>
<h3>1.2.6、删除</h3>
<p>db.集合.deleteOne(条件);</p>
<p>db.users.deleteOne({age:{'﹩gte':10}}); &nbsp;删除年龄&gt;=10岁的数据</p>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220916150100565-2059066722.png" alt="" loading="lazy"></p>
<p>删除多条</p>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220916150319752-28069085.png" alt="" loading="lazy"></p>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220916150520684-1300511256.png" alt="" loading="lazy"></p>
<h1>二、NodeJS访问MongoDB</h1>
<p>MongoDB对许多平台都提供驱动可以访问数据库,如C#、Java、Node.js等。这里以Node.js为例。</p>
<h2>2.1、安装MongoDB访问驱动</h2>
<p>使用包管理器,在命令行执行如下指令:</p>
<p>全局安装驱动</p>
<p>npm install mongodb -g</p>
<p>在当前项目中引入mongodb</p>
<p>npm install mongodb --save</p>
<p><img src="https://images2015.cnblogs.com/blog/63651/201612/63651-20161223155230807-1724719163.png" alt=""></p>
<p>这样添加驱动就成功了。</p>
<p>连接数据库</p>
<div class="cnblogs_code">
<pre>const { MongoClient } = require("mongodb");<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">导入依赖对象mongo客户端</span>
<span style="color: rgba(0, 0, 0, 1)">
let url</span>="mongodb://127.0.0.1:27017";<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">数据库连接字符串</span>
<span style="color: rgba(0, 0, 0, 1)">
let client</span>=<span style="color: rgba(0, 0, 255, 1)">new</span> MongoClient(url);<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">实例化一个mongo客户端</span>
<span style="color: rgba(0, 0, 0, 1)">
async </span><span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> run(){
    </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)">{
      await client.connect();</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">连接</span>
      await client.db("nfit").command({ping:1});<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">向数据库nfit发送命令</span>
      console.log("连接数据库成功!"<span style="color: rgba(0, 0, 0, 1)">);
    }
    </span><span style="color: rgba(0, 0, 255, 1)">finally</span><span style="color: rgba(0, 0, 0, 1)">{
      await client.close();
    }
}

run().</span><span style="color: rgba(0, 0, 255, 1)">catch</span>(console.log);</pre>
</div>
<p>运行结果:</p>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220915151709643-835260045.png" alt="" loading="lazy"></p>
<p>注意连接关键字不允许使用localhost</p>
<h2>2.2、添加数据</h2>
<p>在项目的根目录下新建一个db.js文件,使用Node.js操作MongoDB。</p>
<p><img src="https://images2015.cnblogs.com/blog/63651/201612/63651-20161223155442214-697244536.png" alt=""></p>
<p>示例代码:</p>
<div class="cnblogs_code">
<pre>const { MongoClient } = require("mongodb");<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">依赖MongoClient</span>
<span style="color: rgba(0, 0, 0, 1)">
let client</span>=<span style="color: rgba(0, 0, 255, 1)">new</span> MongoClient("mongodb://127.0.0.1:27017");<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">实例化一个客户端</span>
<span style="color: rgba(0, 0, 0, 1)">
async </span><span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> run(){
    </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)">{
      let db</span>=await client.db("nfit");<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获取数据库</span>
      let students=await db.collection("students");<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获取集合,表</span>
      let doc={id:202201,name:"tom",age:19};<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">将添加的数据对象</span>
      let result=await students.insertOne(doc);<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">执行向数据库中添加数据并等待响应结果</span>
<span style="color: rgba(0, 0, 0, 1)">      console.log(result);
    }
    </span><span style="color: rgba(0, 0, 255, 1)">finally</span><span style="color: rgba(0, 0, 0, 1)">{
      await client.close();</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">关闭数据库</span>
<span style="color: rgba(0, 0, 0, 1)">    }
}

run().</span><span style="color: rgba(0, 0, 255, 1)">catch</span>(console.log);</pre>
</div>
<p>运行结果:</p>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220919093835709-2027709061.png" alt="" width="590" height="154" loading="lazy"></p>
<p>查看数据库:</p>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220919093855421-1264027293.png" alt="" width="614" height="424" loading="lazy"></p>
<p>添加多条数据</p>
<div class="cnblogs_code">
<pre>const { MongoClient } = require("mongodb");<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">依赖MongoClient</span>
<span style="color: rgba(0, 0, 0, 1)">
let client</span>=<span style="color: rgba(0, 0, 255, 1)">new</span> MongoClient("mongodb://127.0.0.1:27017");<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">实例化一个客户端</span>
<span style="color: rgba(0, 0, 0, 1)">
async </span><span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> run(){
    </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)">{
      let db</span>=await client.db("nfit");<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获取数据库</span>
      let students=await db.collection("students");<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获取集合,表</span>
      let docs=[{id:202202,name:"rose",age:17},{id:202203,name:"mark",age:18}];<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">将添加的数据对象</span>
      let result=await students.insertMany(docs);<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">执行向数据库中添加数据并等待响应结果</span>
<span style="color: rgba(0, 0, 0, 1)">      console.log(result);
    }
    </span><span style="color: rgba(0, 0, 255, 1)">finally</span><span style="color: rgba(0, 0, 0, 1)">{
      await client.close();</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">关闭数据库</span>
<span style="color: rgba(0, 0, 0, 1)">    }
}

run().</span><span style="color: rgba(0, 0, 255, 1)">catch</span>(console.log);</pre>
</div>
<p>运行结果:</p>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220919094142362-1315595234.png" alt="" width="605" height="202" loading="lazy"></p>
<p>&nbsp;</p>
<p>&nbsp;<img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220919094200941-1488982422.png" alt="" loading="lazy"></p>
<p>更多</p>
<h2>2.3、修改数据</h2>
<p>示例代码:</p>
<div class="cnblogs_code">
<pre>const { MongoClient } = require("mongodb"<span style="color: rgba(0, 0, 0, 1)">);
let client</span>=<span style="color: rgba(0, 0, 255, 1)">new</span> MongoClient("mongodb://127.0.0.1:27017"<span style="color: rgba(0, 0, 0, 1)">);

async </span><span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> run(){
    </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)">{
      let db</span>=await client.db("nfit"); <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获取数据库</span>
      let students=await db.collection("students");<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获取集合</span>
      let filter={id:202201};<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">要更新的数据的过滤条件</span>
      let result=await students.updateOne(filter,{$set:{name:"汤姆"}});<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">执行更新单条数据</span>
<span style="color: rgba(0, 0, 0, 1)">      console.log(result);
    }
    </span><span style="color: rgba(0, 0, 255, 1)">finally</span><span style="color: rgba(0, 0, 0, 1)">{
      await client.close();</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">关闭</span>
<span style="color: rgba(0, 0, 0, 1)">    }
}

run().</span><span style="color: rgba(0, 0, 255, 1)">catch</span>(console.log);</pre>
</div>
<p>运行结果:</p>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220919095258119-230537965.png" alt="" loading="lazy"></p>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220919095310701-159021645.png" alt="" loading="lazy"></p>
<p>&nbsp;更多</p>
<h2>2.4、查询数据</h2>
<h3>2.4.1、查询单条记录</h3>
<p>示例代码:</p>
<div class="cnblogs_code">
<pre>const { MongoClient } = require("mongodb"<span style="color: rgba(0, 0, 0, 1)">);
let client</span>=<span style="color: rgba(0, 0, 255, 1)">new</span> MongoClient("mongodb://127.0.0.1:27017"<span style="color: rgba(0, 0, 0, 1)">);

async </span><span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> run(){
    </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)">{
      let db</span>=await client.db("nfit"); <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获取数据库</span>
      let students=await db.collection("students");<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获取集合</span>
<span style="color: rgba(0, 0, 0, 1)">
      let filter</span>={id:202201};<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">过滤条件</span>
      let obj=await students.findOne(filter);<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">根据过滤条件查找单条数据</span>
<span style="color: rgba(0, 0, 0, 1)">      console.log(obj);
    }
    </span><span style="color: rgba(0, 0, 255, 1)">finally</span><span style="color: rgba(0, 0, 0, 1)">{
      await client.close();</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">关闭</span>
<span style="color: rgba(0, 0, 0, 1)">    }
}

run().</span><span style="color: rgba(0, 0, 255, 1)">catch</span>(console.log);</pre>
</div>
<p>运行结果:</p>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220919095731065-1775743838.png" alt="" width="552" height="189" loading="lazy"></p>
<h3>2.4.2、查询多条记录</h3>
<p>直接输出</p>
<div class="cnblogs_code">
<pre>const { MongoClient } = require("mongodb"<span style="color: rgba(0, 0, 0, 1)">);
let client</span>=<span style="color: rgba(0, 0, 255, 1)">new</span> MongoClient("mongodb://127.0.0.1:27017"<span style="color: rgba(0, 0, 0, 1)">);

async </span><span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> run(){
    </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)">{
      let db</span>=await client.db("nfit"); <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获取数据库</span>
      let students=await db.collection("students");<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获取集合</span>
<span style="color: rgba(0, 0, 0, 1)">
      let query</span>={id:{$gte:202201}};<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">查询条件是id大于等于202201</span>
      let cursor=await students.find(query);<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">执行查询并返回游标对象</span>
<span style="color: rgba(0, 0, 0, 1)">
      let result</span>=[];<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">学生数组,返回包装用</span>
<span style="color: rgba(0, 0, 0, 1)">
      await cursor.forEach(data</span>=&gt;result.push(data));<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">遍历游标,取出数据</span>
<span style="color: rgba(0, 0, 0, 1)">
      console.log(result);
    }
    </span><span style="color: rgba(0, 0, 255, 1)">finally</span><span style="color: rgba(0, 0, 0, 1)">{
      await client.close();</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">关闭</span>
<span style="color: rgba(0, 0, 0, 1)">    }
}

run().</span><span style="color: rgba(0, 0, 255, 1)">catch</span>(console.log);</pre>
</div>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220919100514052-72896382.png" alt="" width="755" height="705" loading="lazy"></p>
<p>返回结果</p>
<div class="cnblogs_code">
<pre>const { MongoClient } = require("mongodb"<span style="color: rgba(0, 0, 0, 1)">);
let client</span>=<span style="color: rgba(0, 0, 255, 1)">new</span> MongoClient("mongodb://127.0.0.1:27017"<span style="color: rgba(0, 0, 0, 1)">);

async </span><span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> run(){
    </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)">{
      let db</span>=await client.db("nfit"); <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获取数据库</span>
      let students=await db.collection("students");<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获取集合</span>
<span style="color: rgba(0, 0, 0, 1)">
      let query</span>={id:{$gte:202201}};<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">查询条件是id大于等于202201</span>
      let cursor=await students.find(query);<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">执行查询并返回游标对象</span>
<span style="color: rgba(0, 0, 0, 1)">
      let result</span>=[];<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">学生数组,返回包装用</span>
<span style="color: rgba(0, 0, 0, 1)">
      await cursor.forEach(data</span>=&gt;result.push(data));<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">遍历游标,取出数据</span>

      <span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> result;
    }
    </span><span style="color: rgba(0, 0, 255, 1)">finally</span><span style="color: rgba(0, 0, 0, 1)">{
      await client.close();</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">关闭</span>
<span style="color: rgba(0, 0, 0, 1)">    }
}

run().then(console.log).</span><span style="color: rgba(0, 0, 255, 1)">catch</span>(console.log);</pre>
</div>
<p>更多</p>
<h2>2.5、删除数据</h2>
<p>&nbsp;示例代码:</p>
<div class="cnblogs_code">
<pre>const { MongoClient } = require("mongodb"<span style="color: rgba(0, 0, 0, 1)">);
let client</span>=<span style="color: rgba(0, 0, 255, 1)">new</span> MongoClient("mongodb://127.0.0.1:27017"<span style="color: rgba(0, 0, 0, 1)">);

async </span><span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> run(){
    </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)">{
      let db</span>=await client.db("nfit"); <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获取数据库</span>
      let students=await db.collection("students");<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获取集合</span>
      let filter={id:202201};<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">要删除的数据的过滤条件</span>
      let result= await students.deleteOne(filter);<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">执行删除</span>
<span style="color: rgba(0, 0, 0, 1)">      console.log(result);
    }
    </span><span style="color: rgba(0, 0, 255, 1)">finally</span><span style="color: rgba(0, 0, 0, 1)">{
      await client.close();</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">关闭</span>
<span style="color: rgba(0, 0, 0, 1)">    }
}

run().</span><span style="color: rgba(0, 0, 255, 1)">catch</span>(console.log);</pre>
</div>
<p>运行结果:</p>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220919103341553-850906461.png" alt="" loading="lazy"></p>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220919103409141-981773200.png" alt="" width="655" height="364" loading="lazy"></p>
<h1>三、Nodejs访问MySQL</h1>
<h2>3.1、导入mysql模块</h2>
<p> 1、打开根目录,打开终端,初始化执行npm init -y;<br>
2、导入mysql模块: npm i mysql;</p>
<h2>3.2、访问数据库</h2>
<p>示例以gomall数据库中的student数据库为例</p>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220914141953458-35257013.png" alt="" width="876" height="731" loading="lazy"></p>
<h3>3.2.1、连接并查询</h3>
<div class="cnblogs_code">
<pre>const mysql=require("mysql");<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">依赖mysql模块</span>

<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">创建连接池对象</span>
let pool=<span style="color: rgba(0, 0, 0, 1)">mysql.createPool({
    host:</span>"localhost",<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">主机</span>
    user:"root",<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">用户名</span>
    password:"123456",<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">密码</span>
    database:"gomall"<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">数据库,port可以省去</span>
<span style="color: rgba(0, 0, 0, 1)">});


pool.getConnection((connErr,conn)</span>=&gt;{<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获取连接对象</span>
    pool.query("select id,name,sex from student",(err,results)=&gt;{<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">执行查询</span>
      <span style="color: rgba(0, 0, 255, 1)">if</span>(err) <span style="color: rgba(0, 0, 255, 1)">throw</span> err;<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">如果有错误,则抛出异常</span>
      console.log(JSON.parse(JSON.stringify(results)));<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">转换并输出查询结果</span>
      conn.release();<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">释放连接</span>
<span style="color: rgba(0, 0, 0, 1)">    });
});</span></pre>
</div>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220920090814945-522868261.png" alt="" width="635" height="232" loading="lazy"></p>
<h3>3.2.2、带参数查询</h3>
<div class="cnblogs_code">
<pre>const mysql=require("mysql");<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">依赖mysql模块</span>

<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">创建连接池对象</span>
let pool=<span style="color: rgba(0, 0, 0, 1)">mysql.createPool({
    host:</span>"localhost",<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">主机</span>
    user:"root",<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">用户名</span>
    password:"123456",<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">密码</span>
    database:"gomall"<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">数据库,port可以省去</span>
<span style="color: rgba(0, 0, 0, 1)">});


pool.getConnection((connErr,conn)</span>=&gt;{<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获取连接对象</span>
    pool.query("select id,name,sex from student where sex=?",['boy'],(err,results)=&gt;{<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">执行查询</span>
      <span style="color: rgba(0, 0, 255, 1)">if</span>(err) <span style="color: rgba(0, 0, 255, 1)">throw</span> err;<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">如果有错误,则抛出异常</span>
      console.log(JSON.parse(JSON.stringify(results)));<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">转换并输出查询结果</span>
      conn.release();<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">释放连接</span>
<span style="color: rgba(0, 0, 0, 1)">    });
});</span></pre>
</div>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220920091127767-1637690373.png" alt="" width="492" height="172" loading="lazy"></p>
<h3>3.2.3、新增数据</h3>
<div class="cnblogs_code">
<pre>const mysql=require("mysql");<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">依赖mysql模块</span>

<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">创建连接池对象</span>
let pool=<span style="color: rgba(0, 0, 0, 1)">mysql.createPool({
    host:</span>"localhost",<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">主机</span>
    user:"root",<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">用户名</span>
    password:"123456",<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">密码</span>
    database:"gomall"<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">数据库,port可以省去</span>
<span style="color: rgba(0, 0, 0, 1)">});

let sql</span>="insert into student(name,sex) values(?,?)"<span style="color: rgba(0, 0, 0, 1)">;
pool.getConnection((connErr,conn)</span>=&gt;{<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获取连接对象</span>
    pool.query(sql,['tom','boy'],(err,results)=&gt;{<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">执行添加,指定参数</span>
      <span style="color: rgba(0, 0, 255, 1)">if</span>(err) <span style="color: rgba(0, 0, 255, 1)">throw</span> err;<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">如果有错误,则抛出异常</span>
      console.log(results);<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">输出结果</span>
      conn.release();<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">释放连接</span>
<span style="color: rgba(0, 0, 0, 1)">    });
});</span></pre>
</div>
<p>结果</p>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220920092635617-252600636.png" alt="" width="591" height="309" loading="lazy"></p>
<h3>3.2.4、便捷增加</h3>
<div class="cnblogs_code">
<pre>const mysql=require("mysql");<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">依赖mysql模块</span>

<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">创建连接池对象</span>
let pool=<span style="color: rgba(0, 0, 0, 1)">mysql.createPool({
    host:</span>"localhost",<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">主机</span>
    user:"root",<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">用户名</span>
    password:"123456",<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">密码</span>
    database:"gomall"<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">数据库,port可以省去</span>
<span style="color: rgba(0, 0, 0, 1)">});

let sql</span>="insert into student set ?"<span style="color: rgba(0, 0, 0, 1)">;
let student</span>={name:"rose",sex:"girl"<span style="color: rgba(0, 0, 0, 1)">};
pool.getConnection((connErr,conn)</span>=&gt;{<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获取连接对象</span>
    pool.query(sql,student,(err,results)=&gt;{<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">执行添加,指定参数对象</span>
      <span style="color: rgba(0, 0, 255, 1)">if</span>(err) <span style="color: rgba(0, 0, 255, 1)">throw</span> err;<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">如果有错误,则抛出异常</span>
      console.log(results);<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">输出结果</span>
      conn.release();<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">释放连接</span>
      <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">process.exit(1);//关闭应用</span>
<span style="color: rgba(0, 0, 0, 1)">    });
});</span></pre>
</div>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220920093149170-1210089110.png" alt="" width="540" height="262" loading="lazy"></p>
<h3>3.2.5、更新数据</h3>
<div class="cnblogs_code">
<pre>const mysql=require("mysql");<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">依赖mysql模块</span>

<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">创建连接池对象</span>
let pool=<span style="color: rgba(0, 0, 0, 1)">mysql.createPool({
    host:</span>"localhost",<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">主机</span>
    user:"root",<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">用户名</span>
    password:"123456",<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">密码</span>
    database:"gomall"<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">数据库,port可以省去</span>
<span style="color: rgba(0, 0, 0, 1)">});

let sql</span>="update student set name=?,sex=? where id=?"<span style="color: rgba(0, 0, 0, 1)">;
pool.getConnection((connErr,conn)</span>=&gt;{<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获取连接对象</span>
    pool.query(sql,['mark','boy',34],(err,results)=&gt;{<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">执行更新,指定参数</span>
      <span style="color: rgba(0, 0, 255, 1)">if</span>(err) <span style="color: rgba(0, 0, 255, 1)">throw</span> err;<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">如果有错误,则抛出异常</span>
      console.log(results);<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">输出结果</span>
      conn.release();<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">释放连接</span>
<span style="color: rgba(0, 0, 0, 1)">    });
});</span></pre>
</div>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220920093534537-1788637486.png" alt="" width="549" height="205" loading="lazy"></p>
<h3>3.2.6、便捷更新数据</h3>
<div class="cnblogs_code">
<pre>const mysql=require("mysql");<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">依赖mysql模块</span>

<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">创建连接池对象</span>
let pool=<span style="color: rgba(0, 0, 0, 1)">mysql.createPool({
    host:</span>"localhost",<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">主机</span>
    user:"root",<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">用户名</span>
    password:"123456",<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">密码</span>
    database:"gomall"<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">数据库,port可以省去</span>
<span style="color: rgba(0, 0, 0, 1)">});

let sql</span>="update student set ? where id=?"<span style="color: rgba(0, 0, 0, 1)">;
let student</span>={name:"jone",sex:'boy'<span style="color: rgba(0, 0, 0, 1)">};
pool.getConnection((connErr,conn)</span>=&gt;{<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获取连接对象</span>
    pool.query(sql,,(err,results)=&gt;{<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">执行更新,指定参数</span>
      <span style="color: rgba(0, 0, 255, 1)">if</span>(err) <span style="color: rgba(0, 0, 255, 1)">throw</span> err;<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">如果有错误,则抛出异常</span>
      console.log(results);<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">输出结果</span>
      conn.release();<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">释放连接</span>
<span style="color: rgba(0, 0, 0, 1)">    });
});</span></pre>
</div>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220920094007368-383809394.png" alt="" width="683" height="305" loading="lazy"></p>
<h3>3.2.7、删除数据</h3>
<div class="cnblogs_code">
<pre>const mysql=require("mysql");<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">依赖mysql模块</span>

<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">创建连接池对象</span>
let pool=<span style="color: rgba(0, 0, 0, 1)">mysql.createPool({
    host:</span>"localhost",<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">主机</span>
    user:"root",<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">用户名</span>
    password:"123456",<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">密码</span>
    database:"gomall"<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">数据库,port可以省去</span>
<span style="color: rgba(0, 0, 0, 1)">});

let sql</span>="delete from student where id=?"<span style="color: rgba(0, 0, 0, 1)">;
pool.getConnection((connErr,conn)</span>=&gt;{<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获取连接对象</span>
    pool.query(sql,,(err,results)=&gt;{<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">执行查询</span>
      <span style="color: rgba(0, 0, 255, 1)">if</span>(err) <span style="color: rgba(0, 0, 255, 1)">throw</span> err;<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">如果有错误,则抛出异常</span>
      <span style="color: rgba(0, 0, 255, 1)">if</span>(results.affectedRows===1){<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">如果影响行数为1</span>
            console.log("删除成功"<span style="color: rgba(0, 0, 0, 1)">);
      }
      </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)">{
            console.log(</span>"删除失败"<span style="color: rgba(0, 0, 0, 1)">);
      }
      conn.release();</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">释放连接</span>
<span style="color: rgba(0, 0, 0, 1)">    });
});</span></pre>
</div>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220920094332918-1135662243.png" alt="" width="553" height="101" loading="lazy"></p>
<p>&nbsp;访问数据库脚本如下:</p>
<div class="cnblogs_code">
<pre>const mysql=require("mysql"<span style="color: rgba(0, 0, 0, 1)">);

const pool</span>=<span style="color: rgba(0, 0, 0, 1)">mysql.createPool({
    host:</span>"localhost"<span style="color: rgba(0, 0, 0, 1)">,
    user:</span>"root"<span style="color: rgba(0, 0, 0, 1)">,
    password:</span>"123456"<span style="color: rgba(0, 0, 0, 1)">,
    database:</span>"gomall"<span style="color: rgba(0, 0, 0, 1)">,
    port:</span>3306<span style="color: rgba(0, 0, 0, 1)">
});

</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">查询</span>
pool.query("select * from student",(err,results)=&gt;<span style="color: rgba(0, 0, 0, 1)">{
    results</span>=<span style="color: rgba(0, 0, 0, 1)">JSON.parse(JSON.stringify(results));
    results.forEach((stu,index)</span>=&gt;<span style="color: rgba(0, 0, 0, 1)">{
      console.log(stu.id,stu.name,stu.sex);
    });
});

</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">增加</span>
let sql="insert into student(name,sex) values(?,?)"<span style="color: rgba(0, 0, 0, 1)">;
pool.query(sql,[</span>'rose','girl'],(err,results)=&gt;<span style="color: rgba(0, 0, 0, 1)">{
    </span><span style="color: rgba(0, 0, 255, 1)">if</span>(err) <span style="color: rgba(0, 0, 255, 1)">throw</span><span style="color: rgba(0, 0, 0, 1)"> err;
    </span><span style="color: rgba(0, 0, 255, 1)">if</span>(results.affectedRows===1<span style="color: rgba(0, 0, 0, 1)">){
      console.log(</span>"增加成功!"<span style="color: rgba(0, 0, 0, 1)">);
    }
});

</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">便捷增加</span>
sql="insert into student set ?"<span style="color: rgba(0, 0, 0, 1)">;
let student</span>={name:"mark",sex:"boy"<span style="color: rgba(0, 0, 0, 1)">};
pool.query(sql,student,(err,results)</span>=&gt;<span style="color: rgba(0, 0, 0, 1)">{
    </span><span style="color: rgba(0, 0, 255, 1)">if</span>(err) <span style="color: rgba(0, 0, 255, 1)">throw</span><span style="color: rgba(0, 0, 0, 1)"> err;
    </span><span style="color: rgba(0, 0, 255, 1)">if</span>(results.affectedRows===1<span style="color: rgba(0, 0, 0, 1)">){
      console.log(</span>"便捷增加成功!"<span style="color: rgba(0, 0, 0, 1)">);
    }
});

</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">修改</span>
sql="update student set name=? where id=?"<span style="color: rgba(0, 0, 0, 1)">;
pool.query(sql,[</span>'lili',26],(err,results)=&gt;<span style="color: rgba(0, 0, 0, 1)">{
    </span><span style="color: rgba(0, 0, 255, 1)">if</span>(err) <span style="color: rgba(0, 0, 255, 1)">throw</span><span style="color: rgba(0, 0, 0, 1)"> err;
    </span><span style="color: rgba(0, 0, 255, 1)">if</span>(results.affectedRows===1<span style="color: rgba(0, 0, 0, 1)">){
      console.log(</span>"修改成功!"<span style="color: rgba(0, 0, 0, 1)">);
    }
});

</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">便捷修改</span>
sql="update student set ? where id=?"<span style="color: rgba(0, 0, 0, 1)">;
student</span>={name:"mark1",sex:"girl"<span style="color: rgba(0, 0, 0, 1)">};
pool.query(sql,,(err,results)=&gt;<span style="color: rgba(0, 0, 0, 1)">{
    </span><span style="color: rgba(0, 0, 255, 1)">if</span>(err) <span style="color: rgba(0, 0, 255, 1)">throw</span><span style="color: rgba(0, 0, 0, 1)"> err;
    </span><span style="color: rgba(0, 0, 255, 1)">if</span>(results.affectedRows===1<span style="color: rgba(0, 0, 0, 1)">){
      console.log(</span>"便捷修改成功!"<span style="color: rgba(0, 0, 0, 1)">);
    }
});

</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">删除</span>
sql="delete from student where id=?"<span style="color: rgba(0, 0, 0, 1)">;
pool.query(sql,[</span>25],(err,results)=&gt;<span style="color: rgba(0, 0, 0, 1)">{
    </span><span style="color: rgba(0, 0, 255, 1)">if</span>(err) <span style="color: rgba(0, 0, 255, 1)">throw</span><span style="color: rgba(0, 0, 0, 1)"> err;
    </span><span style="color: rgba(0, 0, 255, 1)">if</span>(results.affectedRows===1<span style="color: rgba(0, 0, 0, 1)">){
      console.log(</span>"删除成功!"<span style="color: rgba(0, 0, 0, 1)">);
    }
});</span></pre>
</div>
<p>释放连接:</p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">查询</span>
pool.getConnection((err,conn)=&gt;<span style="color: rgba(0, 0, 0, 1)">{
    pool.query(</span>"select * from student",(err,results)=&gt;<span style="color: rgba(0, 0, 0, 1)">{
      results</span>=<span style="color: rgba(0, 0, 0, 1)">JSON.parse(JSON.stringify(results));
      results.forEach((stu,index)</span>=&gt;<span style="color: rgba(0, 0, 0, 1)">{
            console.log(stu.id,stu.name,stu.sex);
      });
      conn.release();
      process.exit(</span>1<span style="color: rgba(0, 0, 0, 1)">);
    });
});</span></pre>
</div>
<p>参考脚本</p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 1.导入mysql模块</span>
const mysql = require('mysql'<span style="color: rgba(0, 0, 0, 1)">)

</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 2.建立和MySQL数据库的联系</span>
const db =<span style="color: rgba(0, 0, 0, 1)"> mysql.createPool({
    host: </span>'127.0.0.1', <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">数据库的ip地址</span>
    user: 'root', <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">登录数据库的账号</span>
    password: 'hoshi1234', <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">登录数据库的密码</span>
    datebase: 'my_dv_01' <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">指定要操作那个数据库</span>
<span style="color: rgba(0, 0, 0, 1)">})

</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 3.测试mysql模块是否正常工作</span>
db.query('select 1',(err, results) =&gt;<span style="color: rgba(0, 0, 0, 1)"> {
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> mysql工作期间报错了</span>
    <span style="color: rgba(0, 0, 255, 1)">if</span>(err) <span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> console.log(err.message);

    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 能够正常执行SQL语句</span>
<span style="color: rgba(0, 0, 0, 1)">    console.log(results);
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 返回 [ RowDataPacket { '1': 1 } ]</span>
<span style="color: rgba(0, 0, 0, 1)">})


</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 4.查询 users 表中所有数据</span>
const sqlStr = 'select * from my_dv_01.users'<span style="color: rgba(0, 0, 0, 1)">
db.query(sqlStr ,(err, results) </span>=&gt;<span style="color: rgba(0, 0, 0, 1)"> {
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> mysql工作期间报错了</span>
    <span style="color: rgba(0, 0, 255, 1)">if</span>(err) <span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> console.log(err.message);

    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 能够正常执行SQL语句</span>
<span style="color: rgba(0, 0, 0, 1)">    console.log(results);
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 返回 users表的字段</span>
<span style="color: rgba(0, 0, 0, 1)">})


</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 5.插入数据到 users 表中</span>

<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 要插入到表中的数据</span>
const user = { usersname: 'benben', password:'886886'<span style="color: rgba(0, 0, 0, 1)"> }

</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 待执行的 SQL语句 ,英文问号 ? 代表占位符(SQL语法)</span>
const sqlStr2 = 'insert into users (usersname, password) VALUES (?,?)'

<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 使用数组的形式,依次为 ? 占位符指定具体的位置</span>
db.query(sqlStr2, ,(err, results) =&gt;<span style="color: rgba(0, 0, 0, 1)"> {
      </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> mysql工作期间报错了</span>
      <span style="color: rgba(0, 0, 255, 1)">if</span>(err) <span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> console.log(err.message);

      </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 如果执行的是insert into这个插入语句,则results是一个对象</span>
      <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 可以通过results.affectedRows判断是否成功</span>
      <span style="color: rgba(0, 0, 255, 1)">if</span>(results.affectedRows === 1<span style="color: rgba(0, 0, 0, 1)">) {
            console.log(</span>'插入数据成功'<span style="color: rgba(0, 0, 0, 1)">);
            </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 打开MySQL的users表格也能看到新数据</span>
            <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 当前数据只有4条,本条数据id为什么是5?</span>
            <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 因为之前有过4的数据,但是被删除了,id具有唯一性,删除了也不能被其他数据使用</span>
<span style="color: rgba(0, 0, 0, 1)">      }
})


</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 插入数据的便捷方式</span>
const user = { usersname: 'niuniu', password:'000000'<span style="color: rgba(0, 0, 0, 1)"> }

</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 定义待执行的 SQL 语句</span>
const sqlStr = 'insert into my_dv_01.users set ?'

<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 执行 SQL 语句</span>
db.query(sqlStr, user,(err, results) =&gt;<span style="color: rgba(0, 0, 0, 1)"> {
      
      </span><span style="color: rgba(0, 0, 255, 1)">if</span>(err) <span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> console.log(err.message);
      </span><span style="color: rgba(0, 0, 255, 1)">if</span>(results.affectedRows === 1<span style="color: rgba(0, 0, 0, 1)">) {
            console.log(</span>'插入数据成功'<span style="color: rgba(0, 0, 0, 1)">);
      }
})


</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 如何更新用户的信息(UPDATE 语句用于更新表中已存在的记录)</span>

<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 要插入到表中的数据</span>
const user = { id: 6, usersname: '犇犇', password:'000111'<span style="color: rgba(0, 0, 0, 1)"> }

</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 定义SQL语句</span>
const sqlStr = 'update my_dv_01.users set usersname=?, password=? where id=?'

<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 执行SQL语句</span>
db.query(sqlStr,, (err, results) =&gt;<span style="color: rgba(0, 0, 0, 1)"> {
    </span><span style="color: rgba(0, 0, 255, 1)">if</span>(err) <span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> console.log(err.message);
    </span><span style="color: rgba(0, 0, 255, 1)">if</span>(results.affectedRows === 1<span style="color: rgba(0, 0, 0, 1)">) {
      console.log(</span>'插入数据成功'<span style="color: rgba(0, 0, 0, 1)">);
    }
})

</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 更新用户信息的便捷方式(数据对象的每个属性和字段一一对应的情况下可使用)</span>
const user = { id: 6, usersname: '夸夸牛', password:'000111'<span style="color: rgba(0, 0, 0, 1)"> }

</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 定义SQL语句</span>
const sqlStr = 'update my_dv_01.users set ? where id=?'

<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 执行SQL语句</span>
db.query(sqlStr,, (err, results) =&gt;<span style="color: rgba(0, 0, 0, 1)"> {
    </span><span style="color: rgba(0, 0, 255, 1)">if</span>(err) <span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> console.log(err.message);
    </span><span style="color: rgba(0, 0, 255, 1)">if</span>(results.affectedRows === 1<span style="color: rgba(0, 0, 0, 1)">) {
      console.log(</span>'插入数据成功'<span style="color: rgba(0, 0, 0, 1)">);
    }
})


</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 删除数据</span><span style="color: rgba(0, 128, 0, 1)">
//</span><span style="color: rgba(0, 128, 0, 1)"> 定义SQL语句</span>
const sqlStr = 'delete from my_dv_01.users where id=?'

<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 执行SQL语句</span><span style="color: rgba(0, 128, 0, 1)">
//</span><span style="color: rgba(0, 128, 0, 1)"> SQL语句中有多个占位符,则必须使用数组为每个占位符指定具体的值</span><span style="color: rgba(0, 128, 0, 1)">
//</span><span style="color: rgba(0, 128, 0, 1)"> 如果只有一个占位符,则可以省略数组</span>
db.query(sqlStr,5,(err,results) =&gt;<span style="color: rgba(0, 0, 0, 1)"> {
    </span><span style="color: rgba(0, 0, 255, 1)">if</span>(err) <span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> console.log(err.message);
      </span><span style="color: rgba(0, 0, 255, 1)">if</span>(results.affectedRows === 1<span style="color: rgba(0, 0, 0, 1)">) {
            console.log(</span>'删除数据成功'<span style="color: rgba(0, 0, 0, 1)">);
      }
})


</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 标记删除</span><span style="color: rgba(0, 128, 0, 1)">
//</span><span style="color: rgba(0, 128, 0, 1)"> 使用delete语句会把数据真正删除掉,非常危险,一般情况下推荐使用标记删除,类似于修改status字段的状态,比如更新成1表示删除;</span>

<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 定义SQL语句</span>
const sqlStr = 'update my_dv_01.users set status=? where id=?'

<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 执行SQL语句</span>
db.query(sqlStr,,(err, results) =&gt;<span style="color: rgba(0, 0, 0, 1)"> {
    </span><span style="color: rgba(0, 0, 255, 1)">if</span>(err) <span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> console.log(err.message);
            </span><span style="color: rgba(0, 0, 255, 1)">if</span>(results.affectedRows === 1<span style="color: rgba(0, 0, 0, 1)">) {
                console.log(</span>'标记删除成功'<span style="color: rgba(0, 0, 0, 1)">);
            }
})</span></pre>
</div>
</div>
<h2>3.3、封装代码</h2>
<p>从上面的示例中可以看出,访问数据库的代码存在许多的重复,为了便于维护与扩展可以将数据库访问代码封装起来。</p>
<p>mysqlutil.js</p>
<div class="cnblogs_code">
<pre>const mysql=require("mysql");<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">依赖mysql模块</span>

<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">创建连接池对象</span>
let pool=<span style="color: rgba(0, 0, 0, 1)">mysql.createPool({
    host:</span>"localhost",<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">主机</span>
    user:"root",<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">用户名</span>
    password:"123456",<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">密码</span>
    database:"gomall"<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">数据库,port可以省去</span>
<span style="color: rgba(0, 0, 0, 1)">});

</span><span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> query(sql,param){
    </span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(0, 0, 255, 1)">new</span> Promise((resolve,reject)=&gt;<span style="color: rgba(0, 0, 0, 1)">{
      pool.getConnection((connErr,conn)</span>=&gt;{<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获取连接对象</span>
            pool.query(sql,param||[],(err,results)=&gt;{<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">执行sql</span>
                <span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)">{
                  </span><span style="color: rgba(0, 0, 255, 1)">if</span><span style="color: rgba(0, 0, 0, 1)">(err) reject(err);
                  resolve(JSON.parse(JSON.stringify(results)));
                }
                </span><span style="color: rgba(0, 0, 255, 1)">finally</span><span style="color: rgba(0, 0, 0, 1)">{
                  conn.release();</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">释放连接</span>
<span style="color: rgba(0, 0, 0, 1)">                }
            });
      });
    });
}

module.exports</span>={query};</pre>
</div>
<p>测试代码:</p>
<div class="cnblogs_code">
<pre>const mysqlutil=require("./mysqlutil");<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">导入mysql工具模块</span>

<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">查询所有</span><span style="color: rgba(0, 128, 0, 1)">
//</span><span style="color: rgba(0, 128, 0, 1)">mysqlutil.query("select * from student").then(console.log).catch(console.log);</span><span style="color: rgba(0, 128, 0, 1)">
//</span><span style="color: rgba(0, 128, 0, 1)">查询并带参数</span><span style="color: rgba(0, 128, 0, 1)">
//</span><span style="color: rgba(0, 128, 0, 1)">mysqlutil.query("select * from student where id=?",).then(console.log).catch(console.log);</span>

<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">执行更新</span>
let sql="update student set ? where id=?"<span style="color: rgba(0, 0, 0, 1)">;
let student</span>={name:"张二",sex:"girl"<span style="color: rgba(0, 0, 0, 1)">};
</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">mysqlutil.query(sql,).then(console.log).catch(console.log);</span>

async <span style="color: rgba(0, 0, 255, 1)">function</span><span style="color: rgba(0, 0, 0, 1)"> findAll(){
    </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)">{
      let result</span>= await mysqlutil.query("select * from student"<span style="color: rgba(0, 0, 0, 1)">);
      </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> result;
      }
    </span><span style="color: rgba(0, 0, 255, 1)">catch</span><span style="color: rgba(0, 0, 0, 1)">(err){
      </span><span style="color: rgba(0, 0, 255, 1)">throw</span><span style="color: rgba(0, 0, 0, 1)"> err;
    }
}

findAll().then(console.log);</span></pre>
</div>
<p><img src="https://img2022.cnblogs.com/blog/63651/202209/63651-20220920103812313-1131628340.png" alt="" width="713" height="397" loading="lazy"></p>
<h1>四、视频</h1>
<p>【Node.js学习总结_张果】 https://www.bilibili.com/video/BV1WW411B78S?share_source=copy_web&amp;vd_source=475a31f3c5d6353a782007cd4c638a8a</p>
<h1>五、作业</h1>
<p>6.1、完成一个图书管理的功能,图书包含(编号,名称,作者,图片,价格),实现:</p>
<p>a)、使用Node.js+Express+Axios+RESTful+MongoDB+Vue技术实现</p>
<p>c)、使用Node.js+Express+Axios+Rest+MySQL+Vue技术实现</p>
<p>页面不一定要完全一样,可以使用UI框架。</p>
<p><img src="https://images2015.cnblogs.com/blog/63651/201612/63651-20161230140932101-1105720214.png" alt="" class="medium-zoom-image"></p><br><br>
来源:https://www.cnblogs.com/best/p/16422421.html
頁: [1]
查看完整版本: Node.js学习笔记(四)——NodeJS访问MongoDB与MySQL数据库