Creating a MySQL table using Node.js


Generally, NoSQL databases (like MongoDB) are more popular among the Node developers. However, it totally depends upon your usecase and choice to choose any DBMS from different database options present. The type of databse you choose mainly depends upon one's project's requirements.

For example, if you need table creation or real-time inserts and want to deal with loads of data, then a NoSQL database is the way to go, whereas if your project deals with more complex queries and transactions, an SQL database will make much more sense.

In this article, we will explain how to connect to a MySQL and then create a new table in it.

Installing the NPM MySQL Dependency

Following are the steps to check your application connection with the MySQL database.

  • Create a new project with a name of your choice, and then navigate to that project.

>> mkdir mysql-test
>> cd mysql-test
  • Create a package.json file using the following command

>> npm init -y

You will get the following output −

Wrote to /home/abc/mysql-test/package.json:
{
   "name": "mysql-test",
   "version": "1.0.0",
   "description": "",
   "main": "index.js",
   "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1"
   },
   "keywords": [],
   "author": "",
   "license": "ISC"
}
  • Installing the MySQL module −

   >> npm install mysql

Output

+ mysql@2.18.1
added 11 packages from 15 contributors and audited 11 packages in 3.264s
found 0 vulnerabilities

Creating the MySQL table using Node

  • Create a JS file with the following name – app.js

  • Copy and Paste the code snippet given below

  • Run the file using the following command −

   >> node app.js

Example

// Checking the MySQL dependency in NPM
var mysql = require('mysql');

// Creating a mysql connection
var con = mysql.createConnection({
   host: "localhost",
   user: "yourusername",
   password: "yourpassword",
   database: "mydb"
});

con.connect(function(err) {
   if (err) throw err;
      console.log("Database connected!");
   var sql = "CREATE TABLE students (name VARCHAR(255), address VARCHAR(255))";
   con.query(sql, function (err, result) {
      if (err) throw err;
         console.log("Table created");
   });
});

Output

The following output will be printed on the console −

Database connected!
Table created

Updated on: 27-Apr-2021

631 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements