Node.js MySQL Create Database


पिछले topic में आपने MySQL connection बनाना सीखा , इस topic में सीखेंगे कि नया database कैसे बनाये हैं।

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

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

//make connecttion
mysql.connect(function(err) {
  if (err) throw err
  
  //if no error this means, connection established successfully !.
  let query = `CREATE DATABASE node_mysql`; 
  mysql.query(query, (error, result) => {
    if (error) throw error
    
    // if no error means , database cereated.
    console.log("Database created : ", result);
  })
});
C:\Users\HP\Desktop\workspace\nodejs>node app.js
Database created :  OkPacket {
  fieldCount: 0,
  affectedRows: 1,
  insertId: 0,
  serverStatus: 2,
  warningCount: 0,
  message: '',
  protocol41: true,
  changedRows: 0
}

तो database create करने वाली query run करने पर output में OkPacket Object return हुआ है , जिसकी property affectedRows:1 यह बताती है कि database create हो चुका है।

Node.js MySQL List Database

जैसा कि मैंने पहले बताया था कि , सभी queries को mysql.query() method के through ही run किया जायगा। तो सभी databases की listing करने के लिए भी simply query ही change करेंगे।

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

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

mysql.connect(function(err) {
  if (err) throw err
  
  //just change the query.
  let query = `SHOW DATABASES`; 
  mysql.query(query, (error, result) => {
    if (error) throw error
    console.log(result);
  })
});
C:\Users\HP\Desktop\workspace\nodejs>node app.js
[
  RowDataPacket { Database: 'information_schema' },
  RowDataPacket { Database: 'laratest' },
  RowDataPacket { Database: 'laravel8auth' },
  RowDataPacket { Database: 'laravelapiauth' },
  RowDataPacket { Database: 'node_mysql' },
  RowDataPacket { Database: 'performance_schema' },
  RowDataPacket { Database: 'phpmyadmin' },
  RowDataPacket { Database: 'test' }
]

Output में आप देख सकते हैं कि , सभी databases का एक array मिला है।

Hey ! I'm Rahul founder of learnhindituts.com. Working in IT industry more than 4.5 years. I love to talk about programming as well as writing technical tutorials and blogs that can help to others .... keep learning :)

Get connected with me - LinkedIn Twitter Instagram Facebook