在本教程中,您将学习如何从node.js应用程序更新MySQL数据库中的数据。
要从node.js应用程序更新数据,请使用以下步骤:
。
通过在Connection对象上调用query()方法来执行UPD语句。
关闭数据库连接。
要连接到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语句。 占位符将被数组中的值替换为数组。 在这个例子中,将id为1的那条记录的completed列将被设置为false。
回调函数的results参数有affectedRows属性,返回UPDATE语句更新的行数。
在执行程序之前,请查看todos表中id为1的行记录信息:
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:workspmysqlnodejsnodejs-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中的数据。
¥ 我要打赏 纠错/补充 收藏
哥,这回真没有了