0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Nest.js と TypeORM で MariaDB に接続

Last updated at Posted at 2021-02-11

次にあるサンプルを実行してみました。
05-sql-typeorm

MariaDB の用意

User: scott
Password: tiger123
Database: my_database

プログラムのクローン

git clone https://github.com/nestjs/nest/

プログラムの準備

cd nest/sample/05-sql-typeorm
npm install

データベースの接続情報の設定

src/app.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UsersModule } from './users/users.module';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'mysql',
      host: 'localhost',
      port: 3306,
      username: 'scott',
      password: 'tiger123',
      database: 'my_database',
      autoLoadEntities: true,
      synchronize: true,
    }),
    UsersModule,
  ],
})
export class AppModule {}

サーバーの起動

npm run start:dev

クライアントでアクセス

$ curl http://localhost:3000/users
[]

MySQL にデータを入れる

insert.sql
insert into user set id =101, firstname='漱石', lastname='夏目';
insert into user set id =102, firstname='鴎外', lastname='森';
insert into user set id =103, firstname='藤村', lastname='島崎';
insert into user set id =104, firstname='治', lastname='太宰';
insert into user set id =105, firstname='龍之介', lastname='芥川';
quit

SQL の実行

mysql -uscott -ptiger123 my_database < insert.sql

クライアントからアクセス

$ curl http://localhost:3000/users | jq .
[
  {
    "id": 101,
    "firstName": "漱石",
    "lastName": "夏目",
    "isActive": true
  },
  {
    "id": 102,
    "firstName": "鴎外",
    "lastName": "森",
    "isActive": true
  },
(省略)

IDを指定してアクセス

$ curl http://localhost:3000/users/104 | jq .
{
  "id": 104,
  "firstName": "治",
  "lastName": "太宰",
  "isActive": true
}

データの削除

curl -X DELETE http://localhost:3000/users/102

データの挿入

$ curl -X POST http://localhost:3000/users -d firstName='左千夫' -d lastName='伊藤'
{"firstName":"左千夫","lastName":"伊藤","id":108,"isActive":true}

次のバージョンで確認しました。

Server version: 10.5.13-MariaDB-0ubuntu0.21.10.1 Ubuntu 21.10
Server version: 8.0.27-0ubuntu0.21.10.1 (Ubuntu)
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?