如何验证MySQL表更新是否成功及访问affectedRows变量
Hey there! Let's walk through your questions about MySQL update operations in your Node.js code.
When you run an UPDATE query in MySQL via Node.js (like your verifyEmailAddressCode function does), the database returns an OkPacket object as the results parameter in your callback. The key indicator here is the affectedRows property:
- If
affectedRows > 0, it means the query found matching rows (that fit youremail_addressandverificationCodeconditions) and successfully updated them. - If
affectedRows = 0, no rows matched the criteria, so no updates were performed.
You can add a check right in your callback to confirm success, like this:
conn.query(updateSQL, function(err, results) { if(err){ conn.release(); return callback(err, null); } // Check if the update was successful const isUpdateSuccessful = results.affectedRows > 0; conn.release(); // Pass back success status along with results return callback(null, { success: isUpdateSuccessful, data: results }); });
affectedRows: 0,如何访问该affectedRows变量? That OkPacket object your query returns is exactly what's stored in the results parameter. You can access affectedRows directly using dot notation:
conn.query(updateSQL, function(err, results) { if(err){ conn.release(); return callback(err, null); } // Access affectedRows directly from the results object const rowsUpdated = results.affectedRows; console.log(`Number of rows updated: ${rowsUpdated}`); // Will log "0" in your case conn.release(); return callback(null, results); });
Since your current code already passes results to the callback, you can also access affectedRows wherever you call verifyEmailAddressCode:
verifyEmailAddressCode('user@example.com', '123456', function(err, results) { if (err) { // Handle error return; } console.log(results.affectedRows); // Logs 0 });
内容的提问来源于stack exchange,提问作者jdotdoe

