First, we will need to install the MySQL package for Node.js. This can be done by running the following command in the terminal:
npm install mysql
Now that we have a connection to the MySQL server, we can create a new database using the following code:
In the above code, we are using the
connection.querymethod to execute a SQL query that creates a new database called "mydb". If the query is successful, it will print "Database created!" to the console.
It's important to note that the
connection.query method is asynchronous, so it is best practice to close the connection after the query is complete. This can be done using the following code:
With this tutorial, you should now have a basic understanding of how to create a MySQL database using Node.js. Remember to always close the connection after your query is complete to avoid any errors.