Setting Up Prisma with MySQL: A Step-by-Step Guid
https://medium.com/@xuwei19850423/setting-up-prisma-with-mysql-a-step-by-step-guid-6a2bd872b985
.env
src\index.js
prisma\schema.prisma
package.json
Setting Up Prisma with MySQL: A Step-by-Step Guid
·
Follow
3 min read·Feb 16, 2024
3
Setting up Mysql
Firstly, let’s install MySQL on Ubuntu by following the instructions provided in the following guide:
https://medium.com/devops-dev/how-to-install-and-configure-mysql-8-x-on-ubuntu-23-x-190b50856450
After installing MySQL and logging in with the root user, we can proceed to create a database and tables. Here are the commands:
Enter your password when prompted.
Creating a database named myFirstDatabase
:
To see the list of databases and let’s use the myFirstDatabase
:
Creating a table named device
with columns id
, name
, and data
:
2 Create project setup
To start, create a project directory and navigate into it:
Next, initialize a TypeScript project and add the Prisma CLI as a development dependency:
This sets up your package.json
with the necessary dependencies for your TypeScript app.
Then, initialize TypeScript:
You can now invoke the Prisma CLI by prefixing it with npx
:
Next, set up your Prisma project by creating your Prisma schema file with the following command:
This command does two things:
creates a new directory called
prisma
that contains a file calledschema.prisma
, which contains the Prisma schema with your database connection variable and schema models
3. Install and generate Prisma Client
To get started with Prisma Client, you need to install the @prisma/client
package:
4. Connect your database (Mysql)
To connect your database, update the url
field of the datasource
block in your Prisma schema (prisma/schema.prisma
) to your database connection URL:
Update your .env
file (vim .env
) with your MySQL database connection URL:
5. Write your first query with Prisma Client
Now that you have generated Prisma Client, you can start writing queries to read and write data in your database. For this guide, let’s use a plain Node.js script (index.ts
) to explore some basic features of Prisma Client:
Run prisma generate
in your terminal to generate Prisma Client. This command reads your Prisma schema and generates Prisma Client based on it. Make sure you run this command in your project directory where your schema.prisma
file is located:
To run the TypeScript script, use the following command:
This command will execute the TypeScript file (index.ts
) using ts-node
.
Reference: https://www.prisma.io/docs/orm/overview/databases/mysql
Last updated