Node.js
Learn how to connect to MySQL databases in Sealos DevBox using Node.js
This guide will walk you through the process of connecting to a MySQL database using Node.js within your Sealos DevBox project.
Prerequisites
- A Sealos DevBox project with Node.js environment
- A MySQL database created using the Database app in Sealos
Install Required Packages
In your Cursor terminal, install the necessary packages:
This command installs:
mysql2
: A MySQL client for Node.js with focus on performancedotenv
: A zero-dependency module that loads environment variables from a.env
file
Connection Setup
Set up the environment and create a client
First, we'll create a .env
file to store our database credentials and a configuration file to load them:
Replace the placeholders with your actual MySQL credentials from the Database app in Sealos.
Next, create a file named db.js
with the following content:
This creates a connection pool, which is more efficient for handling multiple database operations.
Create database operations
Now, let's create a file named dbOperations.js
to handle our database operations:
Create a main script
Finally, let's create a main.js
file to demonstrate all the operations:
Usage
To run the script, use the following command in your Cursor terminal:
This will execute all the operations defined in the main
function, demonstrating the connection to the database, table creation, data insertion, updating, querying, and deletion.
Best Practices
- Use environment variables for database credentials.
- Use connection pooling for better performance.
- Use prepared statements to prevent SQL injection.
- Always handle potential errors using try-catch blocks.
- Close the database connection after operations are complete (in this case, the pool handles this automatically).
Troubleshooting
If you encounter connection issues:
- Verify your database credentials in the
.env
file. - Ensure your MySQL database is running and accessible.
- Check for any network restrictions in your DevBox environment.
- Confirm that the
mysql2
package is correctly installed.
For more detailed information on using MySQL with Node.js, refer to the mysql2 documentation.
Explore with AI
Get AI insights on this article
📤 Share this article
Last updated on