Skip to content

Commit c0fdfeb

Browse files
committed
Add Open Connections To Multiple Databases as a Prisma TIL
1 parent 3cfd11f commit c0fdfeb

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
1212

13-
_1306 TILs and counting..._
13+
_1307 TILs and counting..._
1414

1515
---
1616

@@ -745,6 +745,7 @@ _1306 TILs and counting..._
745745
- [Batch Insert Records With createMany](prisma/batch-insert-records-with-create-many.md)
746746
- [Execute A Raw SQL Query](prisma/execute-a-raw-sql-query.md)
747747
- [Grab A Limited Set Of Records](prisma/grab-a-limited-set-of-records.md)
748+
- [Open Connections To Multiple Databases](prisma/open-connections-to-multiple-databases.md)
748749
- [Specify Alternate Location For Prisma Schema](prisma/specify-alternate-location-for-prisma-schema.md)
749750

750751
### Python
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Open Connections To Multiple Databases
2+
3+
A standard database connection with Prisma is determined by a `DATABASE_URL`
4+
env var set in the `.env` file of your project. Typically, the Prisma client
5+
connecting to that URL will be configured in a separate file and imported
6+
wherever it is used.
7+
8+
```javascript
9+
import {prisma} from './utils/prisma'
10+
```
11+
12+
What if you want to connect to a second, alternate database?
13+
14+
You can create a new Prisma client with the data source configured to be a
15+
different connection URL.
16+
17+
```javascript
18+
import {prisma as primaryPrismaClient} from '@skillrecordings/database'
19+
import {PrismaClient} from '@prisma/client'
20+
21+
const secondaryDatabaseUrl = 'mysql://root@localhost:3399/my-database'
22+
23+
const secondaryPrismaClient = new PrismaClient({
24+
datasources: {
25+
db: {
26+
url: secondaryDatabaseUrl
27+
}
28+
},
29+
})
30+
```
31+
32+
And with that, you can execute queries against both databases.
33+
34+
```javascript
35+
const primaryUserCount = await primaryPrismaClient.user.count()
36+
const secondaryUserCount = await secondaryPrismaClient.user.count()
37+
```
38+
39+
[source](https://www.prisma.io/docs/reference/api-reference/prisma-client-reference#programmatically-override-a-datasource-url)

0 commit comments

Comments
 (0)