DEV Community

loading...

MySQL Database connection from NodeJs application

Bipon Biswas
Front End Engineer at Pridesys IT Ltd, a Software company based in Dhaka, Bangladesh.
・1 min read

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

Discussion (0)