ADVERTISEMENT
ADVERTISEMENT

Home » Node.js

Create another table in same MySQL database by using Node.js

In this article, we are going to learn how to make/create a table in same MYSQL database by using Node.js?
Submitted by Manu Jemini, on November 21, 2017

Prerequisite:

First of all, we are going to require the MySQL module and take it’s reference in a local variable so that we can get all of its methods.

Then create a connection we use MySQL module reference and after that, we establish a connection by using its .createConnection() method and initialize host, username and password and database name.

Now the last thing we do is to invoke .connect() method with a callback function and create a query string to create a table name city with their fields id and cityname. Now using .query() method we execute our query and in callback function, we manage a condition to throw an error if any and shows a message that Table created.

Database details:

  • Hostname: localhost
  • Port number: 3306
  • Username: root
  • Password: 123
  • Database: demo

Server File

//step-1
var mysql = require('mysql');

//step-2
var con = mysql.createConnection({
   host: "127.0.0.1",
    user: "root",
    password: "123",
  database: "demo"
});

//step-3
con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");

//step-4
  var sql = "CREATE TABLE city (id INT PRIMARY KEY, cityname VARCHAR(50))";

//step-5
  con.query(sql, function (err, result) {
    if (err) throw err;
    console.log("Table created");
  });
});

Discussing steps that we have followed in our server file:

  • Require MySQL module.
  • Create Connection variable using mysql.createConnection() method.
  • Connect by using con.connect() method.
  • Creating SQL query.
  • Execute query by using .query() method.
Node.js - create a MySQL table

create a MySQL table in Node.js

If you have any query do comment.

ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.