Interacting with a PostgreSQL database or any other database directly increases the amount of SQL you write.
This can introduce security issues such as SQL injection attacks and limits the portability of your database.
Learn how to use Prisma in Next.js to connect to and interact with a PostgreSQL database.
These are the basic steps for creating a new Next.js software.
Installing the Prisma Client
To start usingPrisma, you will need the prisma and @prisma/client packages.
Install these two packages via npm.
Next, initialize prisma by running the npx prisma init command on the terminal.
Adding the Connection URL
You need a connection URL to connect prisma to yourPostgreSQL database.
This command creates the actual tables in the database.
First, generate the Prisma client.
Then, create a new folder called lib and add a new file named prisma.js in it.
In this file, add the following code to create a prisma client instance.
The pages or components can then fetch data from the API route using anHTTP library like Axios or fetch.
Create the API route by opening the pages/api folder and creating a new subfolder named db.
In this folder, create a file calledcreateuser.jsand add the following handler function.
This function gets the name and email from the request body.
The function returns a JSON object containing the user and the oops message if any.
In one of your components, you might now make a request to this API route.
Then add a simple form containing two input boxes for the name and email and a submit button.
On the form, add an on-submit event that calls a function called handleSubmit.
Now, when the form is submitted, Prisma will create a new user record in the User table.
Besides adding new records to the database, you might also run other SQL commands.