तो जैसा कि आप जानते हैं , कि Node.js server environment है , जो JavaScript को as a server side run कराता है। इसका मतलब है कि Node.js का use database से data fetch करने के लिए भी कर सकते हैं।


इस topic में हम MySQL database के साथ connection कैसे बनाते हैं वो देखेंगे।

What is MySQL

MySQL एक Open Source RDBMS ( Relational Database Management System ) Software है जो Digital Data store और Manage करने के लिए use किया जाता है । MySQL का use लगभग सभी server side programming languages like : PHP , Java , Python , PERL , .NET के साथ use करके Web and Desktop Application में भी किया जाता है।

Install MySQL Driver

आगे बढ़ने से पहले हमें MySQL के लिए driver install करना पड़ेगा। driver install करने के लिए simply नीचे दी गयी command run करें -

npm install mysql

जिस directory में आपने command run की है उस directory में एक file composer.json और node_modules नाम का folder create हो जायगा , जिसमे mysql module files होगी।

basically जो भी packages / modules हम install करते हैं , node_modules folder में उसका source code रहता है। और composer.json file उन modules के बारे में information रखती है जिन्हे आपने install किया है।

MySQL Create Connection

finally अब database connection बनाते हैं -

Copy Fullscreen Close FullscreenRun
// import mysql module
const mysql_module = require('mysql');

// set database credentials
const mysql = mysql_module.createConnection({
  host: "localhost",
  user: "root",
  password: null
});

//finally connect
mysql.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
});
C:\Users\HP\Desktop\workspace\nodejs>node app.js
Connected!

तो basically ऊपर दिए गए example में , database connection के लिए 3 steps follow किये गए हैं। और ज्यादातर chances हैं कि mysql connection हो जायगा।

बैसे createConnection() function में आप database : db_name भी pass कर सकते हैं। तो फिर बाद में आपको database select करने की जरूरत नहीं पड़ेगी।

Node.js में mostly callback functions का ही use होता है , तो अगर आपको callback functions के बारे में knowledge नहीं है तो मैं recommend करूंगा कि पहले आप JavaScript callback functions के working process को समझे।

mysql.query()

MySQL Database connect होने के बाद Node.js में किसी भी तरह की MySQL query run करने के लिए query() method का ही use किया जाता है। जो query के according parameters accept करता है।

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)

Get connected with me. :) LinkedIn Twitter Instagram Facebook

b2eprogrammers