Node.js MySQL Create Table

📔 : NodeJS 🔗

पिछले topic में आपने सीखा कि कैसे Node.js में MySQL database connect करते हैं and कैसे connection queries run करते हैं। इस topic में आप सीखेंगे कि database connect होने के बाद किस तरह से table create और remove करते हैं।


table से किसी भी तरह का operation perform करने के लिए , सबसे पहले तो हमारे pass database selected होना चाहिए , पिछले topic में मैंने एक node_mysql name का database बनाया था। इस बार connection बनाते समय database को भी pass करेंगे।

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

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

Create Table

अब हम node_mysql database में table create करने की query run करेंगे।

Copy Fullscreen Close FullscreenRun
const mysql_module = require('mysql');
const mysql = mysql_module.createConnection({
  host: "localhost",
  user: "root",
  password: null,
  database : "node_mysql"
});

mysql.connect(function(err) {
  if (err) throw err
  
  //query to create a table.
  let query = `CREATE TABLE tbl_users (id INT AUTO_INCREMENT PRIMARY KEY, 
    first_name VARCHAR(30) NOT NULL,
    last_name VARCHAR(30) NOT NULL,
    email VARCHAR(50) NOT NULL,
    about_user VARCHAR(500) DEFAULT NULL, 
    create_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP)`; 

  mysql.query(query, (error, result) => {
    if (error) throw error
    console.log("Table created");
  })
});
C:\Users\HP\Desktop\workspace\nodejs>node app.js
Table created

जैसा कि आप जानते हैं कि MySQL में table create करने के लिए , उसके attributes / columns को उनके type के साथ declare करना पड़ता है।

Show All Tables

सभी tables की listing के लिए simply , query को replace करें और run करें , आपको tables का एक array return होगा।

let query = `SHOW TABLES`; 

  mysql.query(query, (error, result) => {
    if (error) throw error
    console.log( result);
  })

//Output : 
[ RowDataPacket { Tables_in_node_mysql: 'tbl_users' } ]

Delete Table

इसी तरह से किसी भी table को delete करने के लिए delete query run करें।

let query = `SHOW TABLESDROP TABLE table_name`; 

  mysql.query(query, (error, result) => {
    if (error) throw error
    console.log("Table deleted");
  })

I Hope, आपने इस topic में Node.js के साथ MySQL Table के बारे में काफी कुछ सीखा है।

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