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.
xxxxxxxxxx
1
npm install mysql
Step 2 - Import the mysql
module by using require and create a connection with MySQL database.
xxxxxxxxxx
1
const mysql = require('mysql');
2
3
const connection = mysql.createConnection({
4
host: 'localhost', // '127.0.0.1'
5
user: 'root',
6
password: 'password',
7
database: 'database_name'
8
});
9
10
connection.connect(error => {
11
if (error) throw error;
12
});
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.
In this example, we present how to perform a simple SELECT
query on the connected database that selects all rows fron the users
table.
xxxxxxxxxx
1
const mysql = require('mysql');
2
3
const connection = mysql.createconnection({ // gets connection with database
4
host: 'localhost', // '127.0.0.1'
5
user: 'root',
6
password: 'password',
7
database: 'database_name',
8
});
9
10
connection.connect((error) => {
11
if (error) throw error;
12
const query = 'SELECT * FROM ??';
13
const tableName = ['users'];
14
15
connection.query(query, (error, result) => { // sends queries and receives results
16
connection.end(); // closes connection
17
if (error) throw error;
18
console.log(result);
19
});
20
});