← Back

[공부] Prisma 쓰는 법

생각해보면 DB까지 써본적이 별로 없네
썸네일

생각해보면 제가 만든 프로젝트에서 DB를 사용한 적이 없는 거 같습니다.

있어도 백엔드 해주는 친구가 있어서 DB쪽은 다뤄본 적이 없었는데 이참에 Prisma 공부할 겸 써보고

여기에 정리할거다

Prisma란 무엇인가?

ORM 라이브러리임

SQL 말고 JS로 DB 조작할 수 있음 (TS 필수 [type 때문에])

프론트엔드에서 간결하게 백엔드 역할 수행하고 싶으면 이거 씀

실습을 위한 설치

TS 설치

npm install typescript ts-node @types/node --save-dev
npx tsc --init

Prisma 설치

npm init -y
npm install prisma --save-dev
npm install @prisma/client
npm prisma init

폴더 구조

- node_modules/
- prisma/
  - schema.prisma
- .env
- index.ts
- package-lock.json
- package.json
- tsconfig.json

이렇게 구성해주시면 됩니다

저는 Neon 사용해서 DB 연결했는데 각자 원하는 방식으로 하시면 됩니다.

// .env 예시
DATABASE_URL='postgresql://NNN:NNNN@NNNNNNNNNN.NNN.NN.NN.NN/neondb?sslmode=require&channel_binding=require'

// schema.prisma 예시
datasource db {
  provider = "postgresql"     
  url      = env("DATABASE_URL")
}

generator client {
  provider = "prisma-client-js"
}

model User {
  id        Int      @id @default(autoincrement())
  email     String   @unique
  name      String?
  posts     Post[]
  createdAt DateTime @default(now())
}

model Post {
  id        Int      @id @default(autoincrement())
  title     String
  content   String?
  author    User     @relation(fields: [authorId], references: [id])
  authorId  Int
  published Boolean  @default(false)
}

프리즈마에서 테이블 생성

프리즈마는 독자적인 문법으로 테이블을 생성할 수 있습니다

간단한 예시

// SQL
CREATE TABLE person (
    `id` int NOT NULL AUTO_INCREMENT,
    `name` varchar(45),
    `age` int
)

// Prisma
model person {
    id Int @id @default(autoincrement())
    name String? @db.VarChar(45)
    age Int?
}

만약 미리 짜놓은 테이블이 있다면?

npx prisma db pull을 사용해서 불러올 수 있다 반대로 npx prisma db push을 사용해서 짜놓은 DB를 적용할 수 있다

쿼리문 실행

이제 index.ts를 사용해서 테이블을 조작해보자

// index.ts
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

async function main() {
  const newUser = await prisma.user.create({
    data: {
      email: "alice@example.com",
      name: "Alice",
      posts: {
        create: [{ title: "Hello Prisma" }],
      },
    },
  });
  console.log("Created user:", newUser);

  const posts = await prisma.post.findMany({
    where: { published: false },
    include: { author: true },
  });
  console.log("Unpublished posts:", posts);

  const updated = await prisma.user.update({
    where: { id: newUser.id },
    data: { name: "Alice Wonderland" },
  });
  console.log("Updated user:", updated);

  await prisma.post.delete({ where: { id: posts[0].id } });
  console.log("Deleted post with id:", posts[0].id);
}

main()

실행해서 결과 확인

npx ts-node index.ts 를 실행해서 결과를 확인해보자

PS C:\Users\a3162\test> npx ts-node index.ts
Created user: {
  id: 1,
  email: 'alice@example.com',
  name: 'Alice',
  createdAt: 2025-07-06T00:58:13.368Z
}
Unpublished posts: [
  {
    id: 1,
    title: 'Hello Prisma',
    content: null,
    authorId: 1,
    published: false,
    author: {
      id: 1,
      email: 'alice@example.com',
      name: 'Alice',
      createdAt: 2025-07-06T00:58:13.368Z
    }
  }
]
Updated user: {
  id: 1,
  email: 'alice@example.com',
  name: 'Alice Wonderland',
  createdAt: 2025-07-06T00:58:13.368Z
}
Deleted post with id: 1

모든 명령이 잘 실행된 것을 볼 수 있다.

좀 더 알아보기

npx prisma validate 명령어를 통해 스키마를 검사할 수 있다

npx prisma studio 명령어를 통해 DB를 시각화 할 수 있다

이정도만 알면

사용하는데 문제 없고 더 알고싶으면 직접 프로젝트에 도입해보자

[공부] 플러터 시작하기

All in One