Home » Node.js

Create table in MySQL database by using Node.js

In this article, we are going to learn how to create table in our previously created database schema in MYSQL database?
Submitted by Manu Jemini, on November 21, 2017

Prerequisite: Create MYSQL database by using Node.js

As usual, the first step that we are going to take is to require the MySQL module and take its reference in a local variable.

Then create a connection we use MySQL module reference and after that, we establish a connection by using .createConnection() method and initialize host, username, and password of our database. This time we also add database or schema name in our connection.

After that, all we invoke .connect() method with a callback function and create a query string to create a table name clients with their fields id, name, and address. Now using .query() method we execute our query and in the 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 clients (id INT PRIMARY KEY, name VARCHAR(50), address VARCHAR(50))";

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

Discussing above steps:

  • Require module MySql.
  • Creating Connection variable using .createConnection() method.
  • Connect by using .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.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.