Electron Vue3 Typescript Vite使用typeorm操作SQLite

1,安装typeorm和sqlite3:

        npm install typeorm

        npm install sqlite3

2,  新建一个文件data-source.ts。

import { DataSource } from 'typeorm';
import { User } from '../entity/User';
import * as path from 'path';
import { ItemData } from '../entity/ItemData';


export const AppDataSource = new DataSource({
  type: "sqlite",
  database: "database.sqlite",
  synchronize: true,
  logging: false,
  entities: [User, ItemData],
  migrations: [],
  subscribers: [],
});

AppDataSource.initialize()
    .then(async () => {
        console.log("Data Source has been initialized!")

        // const user = new User();
        // user.firstName = "Timber";
        // user.lastName = "Saw";
        // user.age = "25";
        // await AppDataSource.manager.save(user);
        // console.log("Saved a new user with id: " + user.id);
    })
    .catch((err) => {
        console.error("Error during Data Source initialization", err)
    })

export const getDataSource = (delay = 3000): Promise<DataSource> => {
  if (AppDataSource.isInitialized) return Promise.resolve(AppDataSource);

  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (AppDataSource.isInitialized) resolve(AppDataSource);
      else reject("Failed to create connection with database");
    }, delay);
  });
};

3,   在main文件夹中index.ts文件中引入并使用,在创建窗口后调用getDataSource():

import "reflect-metadata";
import {  getDataSource } from '../Config/data-source';


createWindow();
getDataSource();

该文为原创文章,转载请注明原文出处

Author:靓仔建 w: gaolian1025

(希望能帮助到各位,大家的支持是我创作最大动力!现在待业中,希望大家能推荐一下工作。(专注.net C# 6年))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值