gpt4 book ai didi

javascript - 如何获取 SELECT COUNT(*) 的值?

转载 作者:行者123 更新时间:2023-12-02 19:34:53 25 4
gpt4 key购买 nike

我一整天都在努力让 Firefox 服从我的意愿......

我想要:

int c = SELECT COUNT(*) FROM ...

我尝试过 executeAsync({...});,但我认为这是错误的范例,因为我希望立即得到结果。 (mozIStoragePendingStatement 会导致错误)

var count = 0;
var conn = Services.storage.openDatabase(dbfile); // Will also create the file if it does not exist
let statement = conn.createStatement("SELECT COUNT(*) FROM edges LIMIT 42;");
console.log("columns: " + statement.columnCount); // prints "1";
console.log("col name:" + statement.getColumnName(0)); // is "COUNT(*)"

while (statement.executeStep())
count = statement.row.getResultByIndex(0); // "illegal value"
count = statement.row.getString(0); // "illegal value", too
count = statement.row.COUNT(*); // hahaha. still not working
count = statement.row[0]; // hahaha. "undefinded"
count = statement.row[1]; // hahaha. "undefinded"
}
statement.reset();

它基本上可以工作,但我不明白它的值(value)。所有语句(循环内的语句)有什么问题。

感谢您的任何提示...

最佳答案

I've tried executeAsync({...});, but I believe it's the wrong paradigm, as I want the result immediately.

您不应该希望这样,存储 API 是异步的是有原因的。对数据库的同步访问可能会导致随机延迟(例如,如果硬盘驱动器繁忙)。由于您的代码在主线程(为用户界面提供服务的同一线程)上执行,因此当您的代码等待数据库响应时,整个用户界面将挂起。 Mozilla 开发人员在 Firefox 3 中尝试了同步数据库访问,很快注意到它会降低用户体验 - 因此采用异步 API,数据库处理发生在后台线程上,不会阻塞任何内容。

您应该更改代码以异步工作。例如,类似这样的事情应该做:

Components.utils.import("resource://gre/modules/Services.jsm");

var conn = Services.storage.openDatabase(dbfile);
if (conn.schemaVersion < 1)
{
conn.createTable("edges", "s INTEGER, t INTEGER");
conn.schemaVersion = 1;
}

var statement = conn.createStatement("SELECT COUNT(*) FROM edges");
statement.executeAsync({
handleResult: function(resultSet)
{
var row = resultSet.getNextRow();
var count = row.getResultByIndex(0);
processResult(count);
},
handleError: function(error) {},
handleCompletion: function(reason) {}
});

// Close connection once the pending operations are completed
conn.asyncClose();

另请参阅:mozIStorageResultSet , mozIStorageRow .

关于javascript - 如何获取 SELECT COUNT(*) 的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11040200/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com