Languages
[Edit]
EN

Node.js - how to connect with MySQL

0 points
Created by:
Veer-Ahmad
487

In this article, we would like to show you how to use MySQL in Node.js.

 

1. Simple steps

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.

Note:

For applications that require a large number of database connections it is better to use createPool() method instead of createConnection(). For more details read this article.

2. Practical example

In this example, we present how to perform a simple SELECT query on the connected database that selects all rows fron the users table.

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);
  });
});

 

See also

  1. Node.js / MySQL - createConnection vs createPool

References

  1. MySQL package - npm

Alternative titles

  1. Node.js - how to install MySQL driver
  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.

❤️💻 🙂

Join