how to connect mysql using node js stack
Connecting MySQL with Node.js
To connect MySQL with Node.js, you can follow these steps:
Install the
mysql
package using npm:npm install mysql
Require the
mysql
module in your Node.js application:javascript const mysql = require('mysql');
Create a connection pool using the
mysql.createPool()
method:javascript const pool = mysql.createPool({ host: 'localhost', user: 'your_username', password: 'your_password', database: 'your_database' });
Explanation: The
createPool()
method creates a pool of connections to the MySQL database. It takes an object as an argument, where you specify the host, user, password, and database details for your MySQL server.Use the connection pool to execute queries:
javascript pool.query('SELECT * FROM your_table', (error, results, fields) => { if (error) { console.error(error); } else { console.log(results); } });
Explanation: The
query()
method is used to execute SQL queries on the MySQL database. It takes two arguments: the SQL query string and a callback function that handles the query results. The callback function receives three parameters:error
,results
, andfields
. If an error occurs during the query execution, theerror
parameter will contain the error information. Otherwise, theresults
parameter will contain the query results.Close the connection pool when you are done:
javascript pool.end();
Explanation: The
end()
method is used to close the connection pool and release all the connections.
That's it! You have successfully connected MySQL with Node.js and executed a query.