DEV Community

Bipon Biswas
Bipon Biswas

Posted on

MySQL Database connection from NodeJs application

Step 1: install MySql using this command npm install mysql
Step 2: Import var mysql = require('mysql') into index.js file

For connecting with DB write here bellow configuration.

var DatabaseConnectionConfig = {
    host: 'localhost',
    user: 'root',
    password: ''
}
Enter fullscreen mode Exit fullscreen mode

Using createConnection method pass DatabaseConnectionConfig value. Then create a connection.

After running this connection. Then call to connect method. Also check connection connect or not. That's why give a callback function and pass a error parameter.

var con = mysql.createConnection(DatabaseConnectionConfig)

con.connect(function(error){
    if(error){
        console.log('Node DB Connection Failed!')
    }else{
        console.log('Node DB Connection Success!')
    }
})
Enter fullscreen mode Exit fullscreen mode

Create a DB like nodemysql and update bellow property.

var DatabaseConnectionConfig = {
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'nodemysql'
}
Enter fullscreen mode Exit fullscreen mode

index.js file final view

var mysql = require('mysql')

var DatabaseConnectionConfig = {
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'school'
}

var con = mysql.createConnection(DatabaseConnectionConfig)

con.connect(function(error){
    if(error){
        console.log('Node DB Connection Failed!')
    }else{
        console.log('Node DB Connection Success!')
    }
})
Enter fullscreen mode Exit fullscreen mode

Run into terminal using this command. node index.js

Output

Alt Text

Top comments (0)