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

如何解决Ionic+Electron Windows离线应用SQLite初始化报错问题

解决Ionic+Capacitor+Electron环境下SQLite数据库初始化报错问题

在Ionic+Angular应用通过Capacitor打包Electron桌面端时,使用@awesome-cordova-plugins/sqlite插件初始化数据库出现报错:

Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'then')
TypeError: Cannot read properties of undefined (reading 'then')

核心原因是Cordova版SQLite插件在Electron环境下无法正常工作——Capacitor对Cordova插件的Electron支持有限,导致sqlite.create()方法返回undefined,进而触发调用then()的报错。


1. 替换为Capacitor社区原生SQLite插件

使用专门为Capacitor开发的@capacitor-community/sqlite插件,它原生支持Electron平台,提供完整的SQLite关系型数据操作能力。

  • 安装插件:
    npm install @capacitor-community/sqlite
    npx cap sync
    

2. 修改数据库服务代码

替换原有Cordova插件的导入和初始化逻辑,适配新插件的API:

import { Injectable } from '@angular/core';
import { Platform } from '@ionic/angular';
import { Song } from './song';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject } from 'rxjs';
import { CapacitorSQLite, SQLiteConnection, SQLiteDBConnection } from '@capacitor-community/sqlite';

@Injectable({
  providedIn: 'root',
})
export class DbService {
  private dbConnection: SQLiteDBConnection | undefined;
  songsList: BehaviorSubject<any[]> = new BehaviorSubject([]);
  private isDbReady: BehaviorSubject<boolean> = new BehaviorSubject(false);

  constructor(
    private platform: Platform,
    private httpClient: HttpClient
  ) {
    this.initDb();
  }

  async initDb() {
    await this.platform.ready();
    
    // 初始化SQLite连接实例
    const sqlite = new SQLiteConnection(CapacitorSQLite);
    try {
      // 打开或创建目标数据库
      this.dbConnection = await sqlite.openDatabase({
        database: 'positronx_db.db',
        version: 1,
        encrypted: false,
        mode: 'no-encryption'
      });

      // 创建业务表(示例为songs表,可根据需求修改)
      await this.dbConnection.execute(`
        CREATE TABLE IF NOT EXISTS songs (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          title TEXT,
          artist TEXT
        );
      `);

      this.getFakeData();
      this.isDbReady.next(true);
    } catch (error) {
      console.error('数据库初始化失败:', error);
    }
  }

  async getFakeData() {
    if (!this.dbConnection) return;
    
    // 示例:插入测试数据,可替换为从assets读取SQL或HTTP获取数据的逻辑
    const fakeSongs = [
      { title: 'Test Song 1', artist: 'Artist 1' },
      { title: 'Test Song 2', artist: 'Artist 2' }
    ];

    for (const song of fakeSongs) {
      await this.dbConnection.execute(`
        INSERT OR IGNORE INTO songs (title, artist) VALUES (?, ?);
      `, [song.title, song.artist]);
    }

    // 查询数据并更新BehaviorSubject
    const result = await this.dbConnection.query('SELECT * FROM songs;');
    this.songsList.next(result.values);
  }
}

3. 解决Electron运行设备检测问题

执行ionic capacitor run electron提示"No devices or emulators found"时,改用以下方式启动应用:

  • 方式一:打开Electron项目后手动启动
    npx cap open electron
    
    在弹出的Electron项目中,执行npm run start即可启动桌面应用。
  • 方式二:直接运行Electron桌面端
    npx cap run electron --desktop
    

关键说明

  • @capacitor-community/sqlite支持完整的SQL语法,完全满足复杂关系型数据的存储需求,无需替换为Ionic Storage。
  • Electron环境下数据库文件默认存储路径(Windows):C:\Users\<你的用户名>\AppData\Roaming\<应用名称>\databases

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 15:37:52