The process of adding data to a MySQL table using Node and Express typically involves the following steps:
Install the "mysql" module using NPM (Node Package Manager) and require it in the Node.js file.
Connect to the database using the "createConnection" method and provide the required details such as hostname, username, password, and database name.
Use the "query" method to execute an SQL INSERT statement, which inserts the data into the table. The syntax for the statement is as follows:
connection.query('INSERT INTO [table_name] ([column_1], [column_2], [column_3]) VALUES ([value_1], [value_2], [value_3])', function(error, results) {
// handle errors and results
});
Replace [tablename], [column1], [column2], and [column3] with the actual table name and column names. Replace [value1], [value2], and [value_3] with the actual values that you want to insert.
Handle errors and results in the callback function that is passed into the "query" method.
Close the database connection using the "end" method.
The complete code for adding data to a MySQL table using Node and Express would look something like this:
const mysql = require('mysql');
const express = require('express');
const app = express();
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'my_database'
});
app.get('/add-data', function(req, res) {
const data = { name: 'John Doe', email: 'johndoe@example.com', phone: '555-555-5555' };
connection.query('INSERT INTO users (name, email, phone) VALUES (?, ?, ?)', [data.name, data.email, data.phone], function(error, results) {
if (error) {
console.log(error);
res.send('Error adding data to database');
} else {
console.log(results);
res.send('Data added to database');
}
});
});
app.listen(3000, function() {
console.log('Server started on port 3000');
});
connection.end();
Asked: 2023-01-01 11:00:00 +0000
Seen: 10 times
Last updated: Jan 22 '23