Node.js+MySQL更新數據

在本教學中,您將學習如何從node.js應用程式更新MySQL資料庫中的數據。

要從node.js應用程式更新數據,請使用以下步驟:

要連接到MySQL資料庫,我們將使用以下config.js模組,其中包含MySQL資料庫伺服器的必要資訊,包括主機,用戶,密碼和數據庫。

let config = {
  host    : 'localhost',
  user    : 'root',
  password: '123456',
  database: 'todoapp'
};

module.exports = config;

更新數據示例

以下update.js程式根據特定的ID來更新託管的狀態。

let mysql = require('mysql');
let config = require('./config.js');

let connection = mysql.createConnection(config);

// update statment
let sql = `UPDATE todos
           SET completed = ?
           WHERE id = ?`;

let data = [false, 1];

// execute the UPDATE statement
connection.query(sql, data, (error, results, fields) => {
  if (error){
    return console.error(error.message);
  }
  console.log('Rows affected:', results.affectedRows);
});

connection.end();

在這個例子中,我們在UPDATE語句中使用了占位符(?)。

當通過在連接對象上調用query()方法執行UPDATE語句時,以數組的形式將數據傳遞給UPDATE語句。 占位符將被數組中的值替換為數組。 在這個例子中,將id1的那條記錄的completed列將被設置為false

回調函數的results參數有affectedRows屬性,返回UPDATE語句更新的行數。

在執行程式之前,請查看todos表中id1的行記錄資訊:

mysql> SELECT * FROM todos WHERE id = 1;
+----+-------------------------------+-----------+
| id | title                         | completed |
+----+-------------------------------+-----------+
|  1 | Learn how to insert a new row |         1 |
+----+-------------------------------+-----------+
1 row in set (0.00 sec)

現在,我們來運行上面update.js程式。

F:\worksp\mysql\nodejs\nodejs-connect>node update.js
openssl config failed: error:02001003:system library:fopen:No such process
Rows affected: 1

程式返回一條消息,指示受影響的行數為1, 我們可以在資料庫中再次查看它,如下所示:

mysql> SELECT * FROM todos WHERE id = 1;
+----+-------------------------------+-----------+
| id | title                         | completed |
+----+-------------------------------+-----------+
|  1 | Learn how to insert a new row |         0 |
+----+-------------------------------+-----------+
1 row in set (0.00 sec)

您可以看到,completed列中的值已更新為0,在node.js中為false

在本教學中,我們向您展示了如何從node.js應用程式更新MySQL中的數據。


上一篇: MySQL+Python連接和操作 下一篇:無