,

Creating a Database Table Using Express JS Made Simple – PART-3

Posted by

How to easily create a table in a database using Express JS PART-3

How to easily create a table in a database using Express JS PART-3

In this tutorial, we will continue building a simple web application using Express JS and MySQL. In the previous parts, we have covered setting up the project and creating a connection to the database. Now, we will focus on creating a table in the database using Express JS.

Step 1: Install MySQL module

Before we start creating a table in the database, make sure to install the mysql module. You can do this by running the following command in your terminal:

npm install mysql

Step 2: Create a table

First, we need to create a new file called create-table.js in the project directory. In this file, we will write the code to create a table in the database. Here’s an example of how to create a table using Express JS:

“`javascript
// Require the mysql module
const mysql = require(‘mysql’);

// Create a connection to the database
const connection = mysql.createConnection({
host: ‘localhost’,
user: ‘root’,
password: ‘password’,
database: ‘mydatabase’
});

// Connect to the database
connection.connect();

// Create a table
const sql = “CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), email VARCHAR(255))”;
connection.query(sql, (err, result) => {
if (err) throw err;
console.log(“Table created”);
});

// Close the connection
connection.end();
“`

Make sure to replace the host, user, password, and database with your own database details. Save the file and run it using the following command:

node create-table.js

Step 3: Test the table creation

After running the create-table.js file, go to your MySQL workbench or command line and check if the table customers has been created in your database. You should see the table with the columns id, name, and email as defined in the code above.

Conclusion

Congratulations! You have successfully created a table in your database using Express JS. In the next part of this series, we will cover how to insert data into the table using Express JS. Stay tuned for more tutorials!