在Thunderbird中查询SQLite数据库

时间:2015-12-11 15:38:39

标签: javascript sqlite thunderbird thunderbird-addon

我想为使用SQLite数据库的Thunderbird制作一个小插件。我用“SQLite Manager”创建了我的数据库。 问题是,当我访问数据库时,我收到它是空的消息。但事实并非如此!

数据库:

----------------------------
| table1 | table2 | table3 |
----------------------------
|  ...   |  ...   |  ...   |
|  ...   |  ...   |  ...   |
----------------------------

这是JavaScript代码。它应该返回表的名称,但我得到0。

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

  Task.spawn(function() {
    let db;
    let result;
    try {

      db = yield Sqlite.openConnection({ path: "db.sqlite" });
      result = yield db.execute("SELECT name FROM sqlite_master WHERE type='table'");

      alert(result.length);

    } catch (ex) {
      alert("error: " + ex);
    } finally {
      if (db) yield db.close();
    }
  });

可以告诉我我做错了吗?

是否可以在Thunderbird中导入然后读取已存在的数据库?

谢谢!

1 个答案:

答案 0 :(得分:1)

查看source code for Sqlite.jsm,路径始终与配置文件相关。但是,您可以访问模块的后台传递,并从openConnection复制/粘贴代码。这是保存模块中可用的未导出符号的对象。像这样:

Components.utils.import("resource://gre/modules/FileUtils.jsm");
Components.utils.import("resource://gre/modules/Services.jsm");
var {classes: Cc, interfaces: Ci, utils: Cu} = Components;

function openConnection2(path) {
  let Sqlite = Components.utils.import("resource://gre/modules/Sqlite.jsm", {});
  let file = FileUtils.File(path);
  let identifier = Sqlite.getIdentifierByPath(path);
  let openedOptions = {};

  return new Promise((resolve, reject) => {
    let dbOptions = null;
    Services.storage.openAsyncDatabase(file, dbOptions, (status, connection) => {
      if (!connection) {

        reject(new Error(`Could not open connection to ${path}: ${status}`));
        return;
      }
      log.info("Connection opened");
      try {
        resolve(
          new Sqlite.OpenedConnection(connection.QueryInterface(Ci.mozIStorageAsyncConnection),
                                      identifier, openedOptions));
      } catch (ex) {
        reject(ex);
      }
    });
  });
}

你可以在这里传递自己的路径,这应该是完整的路径。您可以通过将chrome uri转换为文件uri来访问您的数据库:

let uri = Services.io.newURI("chrome://myext/content/db.sqlite", null, null);
let registry = Cc['@mozilla.org/chrome/chrome-registry;1']
                .getService(Ci.nsIChromeRegistry);
let path = registry.convertChromeURL(uri)
                   .QueryInterface(Ci.nsIFileURL)
                   .file.path;

yield openConnection2(path); // in your task

请注意,您需要在install.rdf中指定em:unpack,以确保转换后的uri实际上是文件uri而不是jar:uri。