Skip to content

Latest commit

 

History

History
39 lines (29 loc) · 1.16 KB

open-connections-to-multiple-databases.md

File metadata and controls

39 lines (29 loc) · 1.16 KB

Open Connections To Multiple Databases

A standard database connection with Prisma is determined by a DATABASE_URL env var set in the .env file of your project. Typically, the Prisma client connecting to that URL will be configured in a separate file and imported wherever it is used.

import {prisma} from './utils/prisma'

What if you want to connect to a second, alternate database?

You can create a new Prisma client with the data source configured to be a different connection URL.

import {prisma as primaryPrismaClient} from '@skillrecordings/database'
import {PrismaClient} from '@prisma/client'

const secondaryDatabaseUrl = 'mysql://root@localhost:3399/my-database'

const secondaryPrismaClient = new PrismaClient({
  datasources: {
    db: {
      url: secondaryDatabaseUrl
    }
  },
})

And with that, you can execute queries against both databases.

const primaryUserCount = await primaryPrismaClient.user.count()
const secondaryUserCount = await secondaryPrismaClient.user.count()

source