You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Electron应用中SQLite数据库文件替换导入功能实现求助

嘿,我来帮你搞定这个Electron里的数据库备份导入功能!首先得提个小细节:你原来用fs.readFile处理SQLite文件不太对——SQLite是二进制数据库,用utf8编码读取会直接搞坏文件,咱们直接用文件复制的方式才是正确的路子。下面是完善后的可运行方案:

第一步:先确认依赖引入

在你的AngularJS控制器顶部,先引入Electron和Node.js的核心模块:

// 引入Electron对话框和文件系统模块
const { dialog } = require('electron').remote;
const fs = require('fs');
const path = require('path');
const { app } = require('electron').remote;

第二步:完善导入替换逻辑

我把你的$scope.load函数重写了,加了文件过滤、覆盖确认、错误提示这些实用功能:

$scope.load = function() {
  // 配置对话框:只让用户选SQLite相关文件
  dialog.showOpenDialog({
    title: '选择要导入的SQLite数据库',
    filters: [
      { name: 'SQLite数据库', extensions: ['sqlite', 'db', 'sqlite3'] }
    ],
    properties: ['openFile'] // 限制为单个文件选择
  }).then(result => {
    // 处理用户取消选择的情况
    if (result.canceled || result.filePaths.length === 0) {
      console.log("No file selected");
      return;
    }

    const selectedFilePath = result.filePaths[0];
    // 替换成你现有数据库的实际路径,这里用应用的用户数据目录示例
    const existingDbPath = path.join(app.getPath('userData'), 'your-app-database.db');

    // 检查现有数据库是否存在,弹出确认覆盖的提示
    if (fs.existsSync(existingDbPath)) {
      dialog.showMessageBox({
        type: 'warning',
        title: '确认覆盖',
        message: '现有数据库已存在,确定要替换吗?',
        buttons: ['取消', '确定']
      }).then(msgResult => {
        if (msgResult.response === 1) { // 用户点击了确定
          replaceDatabase(selectedFilePath, existingDbPath);
        }
      });
    } else {
      // 现有数据库不存在,直接复制导入
      replaceDatabase(selectedFilePath, existingDbPath);
    }
  }).catch(err => {
    console.error('打开文件对话框出错:', err);
    dialog.showMessageBox({
      type: 'error',
      title: '操作失败',
      message: `打开选择框出错:${err.message}`
    });
  });
};

// 封装数据库复制替换的核心函数
function replaceDatabase(sourcePath, targetPath) {
  // 用异步复制避免阻塞UI
  fs.copyFile(sourcePath, targetPath, (err) => {
    if (err) {
      console.error('复制数据库失败:', err);
      dialog.showMessageBox({
        type: 'error',
        title: '导入失败',
        message: `无法替换数据库:${err.message}`
      });
      return;
    }

    // 导入成功提示,这里可以加重新连接数据库的逻辑
    dialog.showMessageBox({
      type: 'info',
      title: '导入成功',
      message: '数据库已成功替换!'
    });
    // 比如调用你的SQLite初始化函数,重新加载数据
    // $scope.initDatabase();
  });
}

关键注意事项

  • Electron版本兼容:如果你的Electron是10及以上版本,默认禁用了remote模块,需要在main.js的窗口配置里开启:
    // main.js中创建BrowserWindow的配置
    const mainWindow = new BrowserWindow({
      // 其他配置项...
      webPreferences: {
        enableRemoteModule: true,
        contextIsolation: false // 用AngularJS的话可能需要关闭这个,或者改用preload脚本
      }
    });
    
  • 路径安全性:用app.getPath('userData')获取应用的专属用户数据目录,这里存储数据库不会有权限问题,也不会被用户误删。
  • 二进制文件处理:一定要用fs.copyFile而不是读文件内容再写入——SQLite是二进制格式,读写文本编码会直接损坏数据库文件。

内容的提问来源于stack exchange,提问作者Tadej Vozlic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:11:08