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.
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 ofcreateConnection()
. 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);
});
});