0
点赞
收藏
分享

微信扫一扫

使用 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 条评论