javascript - 有没有办法使用 node.js 知道 mysql 表中是否存在一行?
问题描述
我正在尝试创建一个函数,如果它检测到包含 nodejs 中特定列中的值的行,则返回 true。
我尝试使用 query() 中的结果变量但没有成功:
let rowexists = (mystring) => {
let exists = false;
let sql = "SELECT EXISTS( SELECT 1 FROM mytable WHERE `mycolumn` = '" + mystring + "')";
connection.query(sql, function(error, result, field){
console.log((result[sql]));
console.log(exists);
exists = (result[sql]);
});
return exists;
}
console.log(rowexists("myvalue"));
事件如果存在值为“myvalue”的行(存在),rowexists() 始终返回 false。
重要编辑:
我的问题不在于这是异步的,而在于两者都是
console.log((result[sql]));
和
console.log(exists);
返回未定义。
解决方案
承诺是在这种情况下有用的东西。
您遇到的问题是您的查询在函数返回时尚未完成运行。因此,返回一个 Promise 后,我们可以稍后返回该值。
旁注:在使用 SQL 数据库时,您应该使用准备好的查询。
let rowexists = (mystring) => {
// Return a new promise
return new Promise(resolve => {
// Create the sql query (this uses placeholders)
// Hard coded values don't need to be placeholders but just for example:
let sql = "SELECT 1 FROM ?? WHERE ?? = ?";
// Query the database replacing the ?? and ? with actual data
connection.query(sql, ['mytable', 'mycolumn', mystring], function(error, result, field){
// Result will either be undefined or a row.
// Convert it to a boolean and return it.
resolve(!!result)
});
});
}
// Get the data
rowexists("myvalue").then(result => console.log(result))
使用 async/await 的自调用函数:
(async function() {
let exists = await rowexists('myothervalue')
console.log(exists)
// The rest of your related code
})()
如果你不喜欢then()
语法,你可以使用async/await
. 您可以通过以下两种方式执行此操作:
使用 async/await 的基本功能:
async function test() {
let exists = await rowexists('mythrirdvalue')
console.log(exists)
// The rest of your related code
}
test()
推荐阅读
- jenkins - 如果现有构建因超时而失败,则触发另一个作业
- php - 是否可以在没有安装卷的 nginx 的情况下将请求传递给 php-fpm
- firebase - 如何上传和接收用户个人资料图片?
- c++ - 字符指针数组和双指针
- android - 从 json (kotlin android) 获取天气结果
- javascript - 提交时的 HTML 验证 - 总是返回 false
- angular - Angular 应用程序中的搜索/过滤器将不起作用
- r - R循环:将记录分配给现有记录最少的类
- python - 根据列名中的子字符串重新排列 Dataframe 列
- ios - WatchKit 并发症:手表并发症集有一个未分配的项目