流浪のwolf

卷帝

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

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))
复制代码

posted on   朱龙旭的网络  阅读(124)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· Blazor Hybrid适配到HarmonyOS系统
· 支付宝 IoT 设备入门宝典(下)设备经营篇
· 万字调研——AI生成内容检测
· 解决跨域问题的这6种方案,真香!
· 一套基于 Material Design 规范实现的 Blazor 和 Razor 通用组件库
历史上的今天:
2022-10-21 打包项目的时候出错 Multiple assets emit different content to the same filename index.html
2022-10-21 yarn 和 npm 不能混合使用
2022-10-21 路由守卫有哪些 ?
点击右上角即可分享
微信分享提示