Skip to main content

MySQL + NodeJS

Beginner guide to connect to MySQL with NodeJS

Start a Node JS project

> mkdir nodejs-mysql> cd nodejs-mysql> npm init -y

install mysql package

> npm i --save mysql

create a server.js file

> touch server.js

Open nodejs-mysql in your favorite editor and add following code to server.js

const mysql = require('mysql')
// create connection object for DB, you can get all below values from the connection stringconst connectionConfig = {    host: '<replace_with_your_db_server>', // if mysql is running locally it may be 'localhost'    user: '<replace_with_user_id_having_access_to_your_db>',    password: '<replace_with_db_password>',    database: '<default_database_to_connect>'}// initialize with connection configconst db = mysql.createConnection(connectionConfig)
// connect to the serverdb.connect(function(err){    if(err) throw err    console.log("MySQL DB connected successfully!")})
// create query for your dbconst sql =`select * from dbName.tableName`;
// query your db    db.query(sql, function(err,result){        if(err) throw err        console.log(result)        Object.keys(result).forEach((key)=>{            console.log(result[key])            })    })

    // don't forget to close your connection    db.end(err=>{        if(err) throw err        console.log('Connection to MySQL is successfully closed')    })}

To run code, run below command in terminal

> node server.js