const mysql = require(‘mysql2’)
//To make the connection between the mysql server and the nodesjs we have to use createConnection function which takes the below object.
const connection = mysql.createConnection({
host: ‘localhost’,//This host tells at which ip your database is present, it could be some ip also rather than the our local machine
// Our mysql server is going to run on the local machine only so it’s host is local machine/ localhost
database: ‘mytestdb’,//For the given user out of the available databases for the given user which database do you want to use
user: ‘myuser’,//When we reach the mysql server using which user do you want to login
password: ‘mypass’
})
//Creating the connection is a synchronous task above function will finish after the connection is successfully made
//function is executed after the connection has been completed been created
connection.query(
CREATE TABLE IF NOT EXISTS persons ( id INTEGER AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50) NOT NULL, age INTEGER NOT NULL, city VARCHAR(30) ),
function(err,results){//Call back function which is called after the execution of the above query
if(err)//If some error would be there then it contains some values otherwise NULL
{
console.error(err)
}
else
{
console.log(‘Table created successfully’)
}
//connection.close();//always the call the connection,call so that no memory leak is there in our program
}
)
//My code is not working