EN
Node.js - MySQL Insert query
0
points
In this article, we would like to show you how to make an SQL Insert query in Node.js.
Note: at the end of this article you can find database preparation SQL queries.
1. INSERT
query example
const mysql = require('mysql');
const connection = mysql.createConnection({ // gets connection with database
host: 'localhost', // '127.0.0.1'
user: 'root',
password: 'password',
database: 'database_name',
});
connection.connect(error => {
if (error) throw error;
const query = 'INSERT INTO `users` (?, ?) VALUES (?, ?)';
const values = ['name', 'role', 'Matt', 'moderator'];
connection.query(query, values, (error, result) => { // sends queries
connection.end(); // closes connection
if (error) throw error;
console.log(connection.sql); // INSERT INTO `users` (name, role) VALUES (Matt, moderator)
});
});
Before:
[
{ id: 1, name: 'John', role: 'admin' },
{ id: 2, name: 'Chris', role: 'moderator' },
{ id: 3, name: 'Kate', role: 'user' },
{ id: 4, name: 'Denis', role: 'moderator' }
]
After:
[
{ id: 1, name: 'John', role: 'admin' },
{ id: 2, name: 'Chris', role: 'moderator' },
{ id: 3, name: 'Kate', role: 'user' },
{ id: 4, name: 'Denis', role: 'moderator' },
{ id: 5, name: 'Matt', role: 'moderator' }
]
2. Insert multiple records
connection.connect(error => {
if (error) throw error;
const query = 'INSERT INTO users (name, role) VALUES ?';
const values = [
['Matt', 'moderator'],
['Peter', 'user']
];
// sends queries
connection.query(query, [values], (error, result) => {
if (error) throw error;
console.log(result);
});
});
const mysql = require('mysql');
const connection = mysql.createConnection({ // gets connection with database
host: 'localhost', // '127.0.0.1'
user: 'root',
password: 'password',
database: 'database_name',
});
connection.connect((error) => {
if (error) throw error;
const query = 'INSERT INTO `users` (name, role) VALUES ?';
const values = [
['Matt', 'moderator'],
['Peter', 'user']
];
connection.query(query, values, (error, result) => { // sends queries
connection.end(); // closes connection
if (error) throw error;
console.log(connection.sql); // INSERT INTO `users` (name, role)
}); // VALUES ('Matt', 'moderator'),
}); // ('Peter', 'user'),
2. Database preparation
create_tables.sql
file:
CREATE TABLE `users` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(100) NOT NULL,
`role` VARCHAR(15) NOT NULL,
PRIMARY KEY (`id`)
)
ENGINE=InnoDB;
insert_data.sql
file:
INSERT INTO `users`
(`name`, `role`)
VALUES
('John', 'admin'),
('Chris', 'moderator'),
('Kate', 'user'),
('Denis', 'moderator');