HTML5 数据库表 - 检查是否为空
我正在尝试编写一个函数来确定 html5 websql 数据库表是否为空。代码如下。我在那里发出警报,看看发生了什么。当此函数运行时,首先会弹出底部的警报。尽管表是空的,但返回值是 false。
function tableisempty() {
tf = false;
query = "SELECT * FROM OLL;";
localDB.transaction(function(transaction){
transaction.executeSql(query, [], function(tx, results){
if (results.rows.length == 0) {
tf = true;
alert ("table has "+results.rows.length+" rows. returning "+tf);
} else {
tf = false;
alert ("table is not empty. returning "+tf);
}
}, errorHandler);
});
alert ("return value is " + tf);
return tf;
}
I'm attempting to write a function to determine if an html5 websql db table is empty. Code is below. I put alerts in there to see what is happening. When this function runs the alert at bottom pops up first. Although the table is empty the return value is false.
function tableisempty() {
tf = false;
query = "SELECT * FROM OLL;";
localDB.transaction(function(transaction){
transaction.executeSql(query, [], function(tx, results){
if (results.rows.length == 0) {
tf = true;
alert ("table has "+results.rows.length+" rows. returning "+tf);
} else {
tf = false;
alert ("table is not empty. returning "+tf);
}
}, errorHandler);
});
alert ("return value is " + tf);
return tf;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据您的评论和 w3 页面,查询正在异步发生。你的问题的解决方案实际上取决于你的 js 代码结构。
选项 1:
将
tf
移到函数外部(并在前面添加var
),并完全删除其前面的 return 和alert。当你的回调被调用时,它会改变 tf 的值,并且代码的其余部分可以引用它,这是正常的。选项2:
根据这个所以问题,你可以能够将您的调用(我猜是在代码的其他地方)从
openDatabase
更改为openDatabaseSync
来启用同步操作。Based on your comment and the w3 page, the query is happening async. The solution to your problem really depends on your js code structure.
Option 1:
Move
tf
outside the function (and add avar
in front) and completely remove the return and alert right before it. When your callback gets called it will change the value of tf and the rest of your code can reference it is normal.Option 2:
according to this SO question, you may be able to just change your call (elsewhere in your code I presume) from
openDatabase
toopenDatabaseSync
to enable synchronous operations.