EN
Node.js - how to connect with MySQL
0
points
In this article, we would like to show you how to use MySQL in Node.js.
Step 1 - Install the mysql
module in your Node project.
npm install mysql
Step 2 - Import the mysql
module by using require and create a connection with MySQL database.
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost', // '127.0.0.1'
user: 'root',
password: 'password',
database: 'database_name'
});
connection.connect(error => {
if (error) throw error;
});
That's it, you've been connected and from now on you can query your database.
Practical example with SELECT query:
const mysql = require("mysql");
const connection = mysql.createconnection({ // gets connection with database
host: "localhost", // '127.0.0.1'
user: "root",
password: "password",
database: "database_name",
});
connection.connect((error) => {
if (error) throw error;
const query = 'SELECT * FROM ??';
const tableName = ['users'];
connection.query(query, (error, result) => { // sends queries and receives results
connection.end(); // closes connection
if (error) throw error;
console.log(result);
});
});