Skip to main content

Connect your database

To connect your database, you need to set the url field of the datasource block in your Prisma schema to your database connection URL:

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

Note that the default schema created by prisma init uses PostgreSQL as the provider. For PlanetScale, you need to edit the datasource block to use the mysql provider instead:

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

You will also need to set the relation mode type to prisma in order to emulate foreign key constraints in the datasource block:

schema.prisma
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
relationMode = "prisma"
}

Note: Since February 2024, you can alternatively use foreign key constraints on a database-level in PlanetScale, which omits the need for setting relationMode = "prisma".

The url is set via an environment variable which is defined in .env:

.env
DATABASE_URL="mysql://janedoe:mypassword@server.us-east-2.psdb.cloud/mydb?sslaccept=strict"

You now need to adjust the connection URL to point to your own database.

The format of the connection URL for your database typically depends on the database you use. PlanetScale uses the MySQL connection URL format, which has the following structure (the parts spelled all-uppercased are placeholders for your specific connection details):

mysql://USER:PASSWORD@HOST:PORT/DATABASE

Here's a short explanation of each component:

  • USER: The name of your database user
  • PASSWORD: The password for your database user
  • PORT: The port where your database server is running (typically 3306 for MySQL)
  • DATABASE: The name of the database

For a database hosted with PlanetScale, the connection URL looks similar to this:

.env
DATABASE_URL="mysql://myusername:mypassword@server.us-east-2.psdb.cloud/mydb?sslaccept=strict"

The connection URL for a given database branch can be found from your PlanetScale account by going to the overview page for the branch and selecting the 'Connect' dropdown. In the 'Passwords' section, generate a new password and select 'Prisma' to get the Prisma format for the connection URL.

Alternative method: connecting using the PlanetScale CLI

Alternatively, you can connect to your PlanetScale database server using the PlanetScale CLI, and use a local connection URL. In this case the connection URL will look like this:

.env
DATABASE_URL="mysql://root@localhost:PORT/mydb"
info

We recommend adding .env to your .gitignore file to prevent committing your environment variables.

To connect to your branch, use the following command:

pscale connect prisma-test branchname --port PORT

The --port flag can be omitted if you are using the default port 3306.