Nodejs Mysql create table

to create the table in MySQL, I have defined 2 steps.

Step:1) firstly create the connection.js file.


const mysql = require('mysql');
const config  = {
  connectionLimit : 10,
  host     : 'localhost', // Database hostname, 
  user     : 'root', // Database Username
  password : 'jnnn23nn', // Database Password,
  database : 'dbname', //Database Name
};

const pool = mysql.createPool(config);
// Export the pool
module.exports = pool;

IN the connection.js file, You have to include mysql package and create the connection pool.

Step:2) Now, create the createtable.js file and include the connection.js file and write the query in this.


const pool  = require('./connection');

pool.getConnection(function(err, connection) {
  if (err) {
    console.error('error in db connection');
    return;
  }
  console.log('db is connected');
  return ;
}); 

pool.query('CREATE TABLE IF not exists users1 (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,name VARCHAR(50) NOT NULL,age INT(2) NOT NULL', function (error, results) {
if (error) throw error;
console.log('result is: ', results);
});

Now, run the createtable.js file.


node createtable.js
Output:-
OkPacket {
fieldCount: 0,
affectedRows: 0,
insertId: 0,
serverStatus: 2,
warningCount: 0,
message: ”,
protocol41: true,
changedRows: 0 }