mirror of
https://github.com/jbranchaud/til
synced 2026-01-02 22:58:01 +00:00
Add Open Connections To Multiple Databases as a Prisma TIL
This commit is contained in:
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
|
||||
|
||||
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
|
||||
|
||||
_1306 TILs and counting..._
|
||||
_1307 TILs and counting..._
|
||||
|
||||
---
|
||||
|
||||
@@ -745,6 +745,7 @@ _1306 TILs and counting..._
|
||||
- [Batch Insert Records With createMany](prisma/batch-insert-records-with-create-many.md)
|
||||
- [Execute A Raw SQL Query](prisma/execute-a-raw-sql-query.md)
|
||||
- [Grab A Limited Set Of Records](prisma/grab-a-limited-set-of-records.md)
|
||||
- [Open Connections To Multiple Databases](prisma/open-connections-to-multiple-databases.md)
|
||||
- [Specify Alternate Location For Prisma Schema](prisma/specify-alternate-location-for-prisma-schema.md)
|
||||
|
||||
### Python
|
||||
|
||||
39
prisma/open-connections-to-multiple-databases.md
Normal file
39
prisma/open-connections-to-multiple-databases.md
Normal file
@@ -0,0 +1,39 @@
|
||||
# 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.
|
||||
|
||||
```javascript
|
||||
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.
|
||||
|
||||
```javascript
|
||||
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.
|
||||
|
||||
```javascript
|
||||
const primaryUserCount = await primaryPrismaClient.user.count()
|
||||
const secondaryUserCount = await secondaryPrismaClient.user.count()
|
||||
```
|
||||
|
||||
[source](https://www.prisma.io/docs/reference/api-reference/prisma-client-reference#programmatically-override-a-datasource-url)
|
||||
Reference in New Issue
Block a user