Electron中使用@journeyapps/sqlcipher连接加密SQLite3数据库报错求助
问题:Electron中使用Sequelize + @journeyapps/sqlcipher连接加密SQLite失败
错误信息
Uncaught Error: Unable to find dialect at @journeyapps/sqlcipher at ConnectionManager._loadDialectModule (B:\rtapp\node_modules\sequelize\lib\dialects\abstract\connection-manager.js:53) at new ConnectionManager (B:\rtapp\node_modules\sequelize\lib\dialects\sqlite\connection-manager.js:18) at new SqliteDialect (B:\rtapp\node_modules\sequelize\lib\dialects\sqlite\index.js:13) at new Sequelize (B:\rtapp\node_modules\sequelize\lib\sequelize.js:194) at tests.html:35
环境信息
- OS: Windows 10
- Node: 20.11.1
- Electron: 6.1.7
- Sequelize: 6.37.1
- @journeyapps/sqlcipher: 5.3.1
package.json 核心配置
{ "name": "rt", "version": "1.0.0", "scripts": { "start": "electron .", "postinstall": " electron-builder install-app-deps", "rebuild": "electron-rebuild -f -w sqlite3", "build": "electron-packager . all" }, "dependencies": { "@journeyapps/sqlcipher": "^5.3.1", "sequelize": "^6.37.1", "sqlite3": "^4.2.0" } }
连接代码
const db_user = new Sequelize("RT","","1234", { dialect: "sqlite", dialectModulePath: '@journeyapps/sqlcipher', storage: path.join(__dirname,'RT.db'), } ); // SQLCipher config db_user.query("PRAGMA cipher_compatibility = 4"); db_user.query("PRAGMA key = '1234'"); async function connectdb(){ try { await db_user.authenticate(); return console.log('Connection has been established successfully.'); } catch (error) { return console.error('Unable to connect to the database:', error); } }
解决方案
1. 修正Sequelize模块引入配置
Sequelize的dialectModulePath需指向模块实际入口,直接使用dialectModule传入已加载的模块更可靠:
const db_user = new Sequelize("RT","","1234", { dialect: "sqlite", dialectModule: require('@journeyapps/sqlcipher'), // 直接传入模块实例 storage: path.join(__dirname,'RT.db'), } );
2. 重新编译适配Electron的原生模块
当前rebuild脚本仅针对sqlite3,需添加@journeyapps/sqlcipher的编译:
修改package.json的scripts:
"rebuild": "electron-rebuild -f -w sqlite3,@journeyapps/sqlcipher"
执行编译命令:
npm run rebuild
3. 调整PRAGMA密钥设置时机
避免在连接未建立时执行SQL,改用afterConnect钩子确保密钥在连接建立后生效:
const db_user = new Sequelize("RT","","1234", { dialect: "sqlite", dialectModule: require('@journeyapps/sqlcipher'), storage: path.join(__dirname,'RT.db'), hooks: { afterConnect: (connection) => { connection.run("PRAGMA cipher_compatibility = 4"); connection.run("PRAGMA key = '1234'"); } } } );
4. 修复版本兼容性问题
Electron 6.1.7对应Node.js 12.x,与当前使用的Node 20.11.1版本差距过大,会导致原生模块编译失败:
- 方案一:升级Electron到v20+版本,匹配Node 20;
- 方案二:降级Node.js到12.x版本,适配Electron 6.1.7。
5. 验证数据库加密格式
确认DB Browser设置密码时使用的SQLCipher版本,若数据库为更高版本加密,需调整cipher_compatibility值(如改为5)。
内容的提问来源于stack exchange,提问作者electronapp
相关产品推荐
相关产品推荐

