typeOrm 教程 创建链接数据库
实体 User :
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm" @Entity() export class User { @PrimaryGeneratedColumn() id: number @Column() firstName: string @Column() lastName: string @Column() age: number }
数据库配置项 :
import "reflect-metadata" import { DataSource } from "typeorm" import { User } from "./entity/User" // 直接设置所有的实体一次性添加到 entitries 属性中 // [__dirname + "/entity/*.js"] export const AppDataSource = new DataSource({ type: "postgres", host: "192.168.33.200", port: 5432, username: "postgres", password: "123456", database: "postgres", synchronize: true, logging: false, entities: [__dirname + "/entity/*.ts"], migrations: [], subscribers: [], })
修改数据库:
import { AppDataSource } from "./data-source" import { User } from "./entity/User" // 初始数据库 AppDataSource.initialize().then(async (connection) => { console.log("Inserting a new user into the database...") const user = new User() // 1. 从数据库获取 User 表 let UserRepository = connection.getRepository(User); // 2. 获取Use表的全部内容 let userToUpdate = await UserRepository.find(); userToUpdate.forEach((e) => { e.firstName = "admin" e.lastName = "123456" e.age = 100 }) // 异步保存 await UserRepository.save(userToUpdate) console.log("Saved a new user with id: " + user.id) }).catch(error => console.log(error))