Node.js - how to connect with MySQL

0 points
Created by:

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',  // ''
    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",  // ''
    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;


  1. MySQL package - npm

Alternative titles

  1. Node.js - how to install MySQL
  2. How to use MySQL in Node
  3. Node.js - install MySQL Driver
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Node.js - MySQL

Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂