Create MySql Table in Node js

Table is a collection of related data. A table contains a set of vertical columns and horizontal rows. A table column is defined when we create a table, later we can alter it and on every data insert a new row is created. A new table creation requires a name of table which is unique in a database, fields name and their data types.

To create a table using Node.js, CREATE TABLE command is used. For this first we make a connection to the database, then write, create query to create the table.

Syntax

CREATE TABLE tablename (column name, column datatype); 

Example

In this given example, we have created a table name 'department'. It contain three fields (id, name and emp_length).

var mysql = require("mysql");
var con = mysql.createConnection({
    host: "hostname",
    user: "username",
    password: "password",
    database: "database"
});
con.connect(function(error){
    if(error) {
        console.log('Error establishing connection to db');
        return;
    }
    console.log('Connection Established'); 
    var createtbl = "CREATE TABLE department (id INT, name VARCHAR(255), emp_length INT(3))";
    con.query(createtbl, function (error) {  
    if(error) { 
        console.log('Error in table creation');
        return;
    }  
    console.log("Table created");  
    });  
});

Open cmd and run the above file as -

node createtable.js

It shows the following output on the console.

nodejs mysql create table


Read more articles


General Knowledge



Learn Popular Language