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: ''
}
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!')
}
})
Create a DB like nodemysql
and update bellow property.
var DatabaseConnectionConfig = {
host: 'localhost',
user: 'root',
password: '',
database: 'nodemysql'
}
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!')
}
})
Run into terminal using this command. node index.js
Output
Top comments (0)