在Node.js中使用Lambda函数进行MySQL查询后返回值,可以使用回调函数或Promise来处理。
使用回调函数的示例代码如下:
const mysql = require('mysql');
exports.handler = (event, context, callback) => {
// 创建MySQL连接
const connection = mysql.createConnection({
host: 'your-hostname',
user: 'your-username',
password: 'your-password',
database: 'your-database'
});
// 连接到MySQL数据库
connection.connect();
// 执行查询
connection.query('SELECT * FROM your_table', (error, results, fields) => {
if (error) {
// 查询出错,调用回调函数返回错误信息
callback(error);
} else {
// 查询成功,调用回调函数返回查询结果
callback(null, results);
}
});
// 关闭MySQL连接
connection.end();
};
使用Promise的示例代码如下:
const mysql = require('mysql');
exports.handler = async (event, context) => {
// 创建MySQL连接
const connection = mysql.createConnection({
host: 'your-hostname',
user: 'your-username',
password: 'your-password',
database: 'your-database'
});
// 连接到MySQL数据库
connection.connect();
// 使用Promise封装查询
const queryPromise = () => {
return new Promise((resolve, reject) => {
connection.query('SELECT * FROM your_table', (error, results, fields) => {
if (error) {
// 查询出错,reject错误信息
reject(error);
} else {
// 查询成功,resolve查询结果
resolve(results);
}
});
});
};
try {
// 执行查询并获取结果
const results = await queryPromise();
// 关闭MySQL连接
connection.end();
// 返回查询结果
return results;
} catch (error) {
// 查询出错,关闭MySQL连接并抛出错误
connection.end();
throw error;
}
};
这两种方法都能够在MySQL查询完成后返回查询结果,具体使用哪种方法取决于你的需求和代码结构。