文章数量
36
访客量
4952
访问量
9817

使用nestjs连接mysql并进行增删改查

阅读量:1800
更新时间:2023-01-02 18:30:57

如何使用nestjs连接mysql,并进行增删改查,首先创建nestjs项目

一、准备nestjs项目

npm i -g @nestjs/cli
nest new project-name

二、目录结构

src
 ├── app.controller.spec.ts
 ├── app.controller.ts
 ├── app.module.ts
 ├── app.service.ts
 └── main.ts

三、创建cats数据库表

name type length
id int 11
title varchar 20
age int 11

四、创建对应文件

1、 创建 cats/cats.entities.ts 文件

import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';

@Entity({ name: 'cats' })
export class Cats {
    @PrimaryGeneratedColumn()
    id: number;

    @Column({ name: 'title' })
    title: string;

    @Column({ name: 'age' })
    age: number;
}

2、 创建 cats/cats.service.ts 文件

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Cats } from './cats.entities';

@Injectable()
export class CatsService {
  constructor(
    @InjectRepository(Cats)
    private catsRepository: Repository,
  ) { }

  findAll(): Promise {
    return this.catsRepository.find();
  }

  findOne(id: number): Promise {
    return this.catsRepository.findOne(id);
  }

  async remove(id: number): Promise {
    await this.catsRepository.delete(id);
  }

  async create(cats: Cats): Promise {
    await this.catsRepository.save(cats);
  }
}

3、创建 cats/cats.controller.ts 文件

import { Controller, Get, Param } from '@nestjs/common';
import { CatsService } from './cats.service';
import { Cats } from './cats.entities';
@Controller('cats')
export class CatsController {
    constructor(private readonly catsService: CatsService) { }
    /**
     * 获取一条数据
     * @param params 
     * @returns 
     */
    @Get('/get/:id')
    async get(@Param() params) {
        return await this.catsService.findOne(params.id);
    }
    /**
     * 获取所有数据
     * @returns 
     */
    @Get("/all")
    async findAll() {
        return await this.catsService.findAll()
    }
    /**
     * 创建数据
     * @param params 
     * @returns 
     */
    @Get('/create/:title/:age')
    async findOne(@Param() params) {
        let cats = new Cats();
        cats.title = params.title;
        cats.age = params.age;
        return await this.catsService.create(cats);
    }
    /**
     * 删除一条数据
     * @param params 
     * @returns 
     */
    @Get('/remove/:id')
    async remove(@Param() params) {
        return await this.catsService.remove(params.id);
    }
}

4、创建 cats/cats.module.ts 文件

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { CatsController } from './cats.controller';
import { Cats } from './cats.entities';
import { CatsService } from './cats.service';

@Module({
    imports: [TypeOrmModule.forFeature([Cats])],
    controllers: [CatsController],
    providers: [CatsService],
})
export class CatsModule { }

5、修改app.module.ts ,使用 npm install --save save @nestjs/typeorm typeorm mysql 安装mysql模板,并连接数据库

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Cats } from './cats/cats.entities';
import { CatsModule } from './cats/cats.module';
import { Connection } from 'typeorm';
@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'mysql',
      host: '127.0.0.1',
      port: 3306,
      username: 'hutu',
      password: 'aa2248',
      database: 'demo',
      entities: [Cats],
      synchronize: true,
    }),
    CatsModule,
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {
  constructor(private connection: Connection) { }
}

五、请求对应的路由

get http://localhost:3000/cats/create/name/19
get http://localhost:3000/cats/get/1
get http://localhost:3000/cats/all
get http://localhost:3000/cats/remove/1