如何为Firefox插件初始化SQLite文件


  1. 插件使用的SQLite数据文件是否可能是使用data.url()访问的文件之一?

  2. 如果是,如何将其移交给Services.storage.openDatabase()

  3. 如果没有,是否可能只在第一次运行附加组件时执行某些代码(CREATE TABLE If EXISTS…)?

插件使用的SQLite数据文件是否可能是使用data.url()访问的文件之一?

没有。从Add-on-SDK1.5开始,扩展在安装时不再压缩,而是作为压缩的XPI文件保存在磁盘上(这对性能有好处)。然而,SQLite需要一个物理文件,而不是档案中的某个文件。

如果没有,是否可能只在第一次运行附加组件时执行某些代码(CREATE TABLE If EXISTS…)?

当然,但你不应该这样做——如果你的数据库文件因为某种原因被删除了怎么办?最好检查数据库是否已经存在:

var dbFile = FileUtils.getFile("ProfD", "foobar.sqlite");
var alreadyExists = dbFile.exists();
var dbConnection = Services.storage.openDatabase(dbFile);
if (!alreadyExists)
  connection.createTable("foo", "id INTEGER PRIMARY KEY, ...");

供参考:FileUtils.jsm

Components.utils.import("resource://gre/modules/Services.jsm");
Components.utils.import("resource://gre/modules/FileUtils.jsm");
let file = FileUtils.getFile("ProfD", ["my_db_file_name.sqlite"]);
let mDBConn = Services.storage.openDatabase(file); // Will also create the file if it does not exist

最新更新