Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

Node.js MySQL 更新


更新表

您可以使用“UPDATE”语句更新表中现有的记录。

示例

将地址列从“Valley 345”覆盖为“Canyon 123”。

var mysql = require('mysql');

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

con.connect(function(err) {
  if (err) throw err;
  var sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Valley 345'";
  con.query(sql, function (err, result) {
    if (err) throw err;
    console.log(result.affectedRows + " 条记录已更新");
  });
});
运行示例 »

请注意 UPDATE 语法中的 WHERE 子句:WHERE 子句指定应更新哪些记录。如果省略 WHERE 子句,则所有记录都将被更新!

将以上代码保存到名为“demo_db_update.js”的文件中,然后运行该文件。

运行“demo_db_update.js”

C:\Users\您的用户名>node demo_db_update.js

这将为您提供以下结果

1 条记录已更新


结果对象

执行查询时,会返回一个结果对象。

结果对象包含有关查询如何影响表的信息。

上面示例中返回的结果对象如下所示

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

可以像这样显示属性的值

示例

返回受影响的行数

console.log(result.affectedRows)

这将产生以下结果

1
×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.