How To Insert Values into a Database Table Using Express JS
Express JS is a popular web application framework for Node.js which is used to build web applications and APIs. One common task when working with databases in web applications is inserting values into a database table. In this article, we will learn how to do that using Express JS.
Setting Up the Database
Before we can insert values into a database table using Express JS, we need to set up a database. For this example, let’s use MySQL as the database and create a table called `users` with columns `id`, `name`, and `email`.
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL
);
Connecting to the Database
Next, we need to establish a connection to the MySQL database using the `mysql` package in Node.js. We can do this by creating a connection pool and providing the database credentials.
const mysql = require('mysql');
// Create a connection pool
const pool = mysql.createPool({
host: 'localhost',
user: 'your_username',
password: 'your_password',
database: 'your_database'
});
// Test the connection
pool.getConnection((err, connection) => {
if (err) throw err;
console.log('Connected to the database');
connection.release();
});
Inserting Values into the Database Table
Now that we have established a connection to the database, we can proceed to insert values into the `users` table. We can do this by executing an SQL INSERT query using the `pool.query` method.
// Define the data to be inserted
const userData = {
name: 'John Doe',
email: 'john@example.com'
};
// Insert the data into the users table
pool.query('INSERT INTO users SET ?', userData, (err, result) => {
if (err) throw err;
console.log('Inserted into users table:', result);
});
Conclusion
In this article, we have learned how to insert values into a database table using Express JS. We first set up a MySQL database and created a table, then connected to the database using the `mysql` package in Node.js, and finally inserted values into the table using the `pool.query` method. This is just a basic example, and in practice, you will need to handle errors and sanitize user input for security. But this should give you a good starting point for working with databases in Express JS.