4

我正在尝试在我的 Angular + Electron 应用程序中使用 node-sqlite3 打开一个 sqlite 数据库文件。

尽管我确保该文件存在并且 Electron 可以读取它,但当我尝试使用以下命令创建 sqlite 数据库时:

import * as sqlite from 'sqlite3';

// ...

const path = `${__dirname}/assets/sqlite.db`;

const fs = require('electron').remote.require('fs');
console.log(path);
if (fs.existsSync(AppConfig.sqlitePath)) {
  console.log('the file exists');
} else {
  console.log('the file does not not');
}

const myDb = new sqlite.Database(path, sqlite.OPEN_READONLY, (error) => {
  console.log(error);
});

该文件存在,因为我得到了正确的console.log消息,它看起来像:

/tmp/.mount_xxxxxx/resources/app.asar.unpacked/dist/assets/sqlite.db

但是,new sqlite.Database(...)由于文件不存在,我收到以下错误:

错误:SQLITE_CANTOPEN:无法打开数据库文件

4

3 回答 3

4

artiebits建议我查看asarUnpack,这确实是正确的方法。


我解决了:

1)将以下内容添加到我的electron-builder.json

"asarUnpack": [
  "dist/assets/sqlite.db"
],

2)替换:

const path = `${__dirname}/assets/sqlite.db`;

和:

const path = `${__dirname}/assets/sqlite.db`.replace('app.asar', 'app.asar.unpacked');
于 2020-02-26T21:32:27.947 回答
0

使用数据库文件的绝对地址

例子:

Linux:

常量路径=“/home/brunodev/Documents/vscode/Git/backend/src/database/database.db”

视窗:

const path = "C:/Users/brunodev/Documents/vscode/Git/backend/src/database/database.db"

于 2021-10-04T01:41:19.407 回答
0

此处使用 extraResources 参数的另一个解决方案:https ://github.com/electron/electron/issues/4644#issuecomment-637030403

# packages.json
"build": {
    ...
    "extraResources": [
      "databaseFolder"
    ],
   ...
}

确保检查数据库文件是否存在然后同步

const path = require('path');
const fse = require('fs-extra')
const Sequelize = require('sequelize');
const dbPath = path.resolve(process.resourcesPath, 'databaseFolder')
const dbFile = path.resolve(dbPath, 'database.sqlite')

const sequelize = new Sequelize({
  dialect: 'sqlite',
  storage: dbFile
})

if (!fse.existsSync(dbPath)) {
  fse.ensureDirSync(dbPath)
  fse.ensureFileSync(dbFile)
  sequelize.sync({ force: true })
}
于 2021-08-20T18:09:12.327 回答