使用 NodeJS 更新 MySQL 中的记录

在本文中,我们将看到如何使用 NodeJS 更新 MySQL 中的记录。我们将从 Node.js 服务器动态更新 MySQL 表值。您可以在更新后使用 select 语句来检查 MySql 记录是否已更新。

在继续之前,请检查以下步骤是否已执行 -

  • MKDIR MySQL测试版

  • CD MySQL测试版

  • npm init -y

  • npm install mysql

上述步骤用于在项目文件夹中安装 Node - mysql 依赖项。

将记录填充到学生表中 -

  • 要将现有记录更新到 MySQL 表中,首先创建一个 app.js 文件

  • 现在将以下代码片段复制粘贴到文件中

  • 使用以下命令运行代码

>> node app.js

// Checking the MySQL dependency in NPM
var mysql = require('mysql');

// Creating a mysql connection
var con = mysql.createConnection({
   host: "localhost",
   user: "yourusername",
   password: "yourpassword",
   database: "mydb"
});

con.connect(function(err) {
   if (err) throw err;
   var sql = "UPDATE student SET address = 'Bangalore' WHERE name = 'John';"
   con.query(sql, function (err, result) {
      if (err) throw err;
      console.log(result.affectedRows + " Record(s) updated.");
      console.log(result);
   });
});

输出

1 Record(s) updated.
OkPacket {
   fieldCount: 0,
   affectedRows: 1, // This will return the number of rows updated.
   insertId: 0,
   serverStatus: 34,
   warningCount: 0,
   message: '(Rows matched: 1 Changed: 1 Warnings: 0', // This will return the
   number of rows matched.
   protocol41: true,
   changedRows: 1 }

// Checking the MySQL dependency in NPM
var mysql = require('mysql');

// Creating a mysql connection
var con = mysql.createConnection({
   host: "localhost",
   user: "yourusername",
   password: "yourpassword",
   database: "mydb"
});

con.connect(function(err) {
   if (err) throw err;
   // Updating the fields with address while checking the address
   var sql = "UPDATE student SET address = 'Bangalore' WHERE address = 'Delhi';"
   con.query(sql, function (err, result) {
      if (err) throw err;
      console.log(result.affectedRows + " Record(s) updated.");
      console.log(result);
   });
});

输出

3 Record(s) updated.
OkPacket {
   fieldCount: 0,
   affectedRows: 3, // This will return the number of rows updated.
   insertId: 0,
   serverStatus: 34,
   warningCount: 0,
   message: '(Rows matched: 3 Changed: 3 Warnings: 0', // This will return the number of rows matched.
   protocol41: true,
   changedRows: 3 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值