Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Mysql Insert Into in NodeJs

Mysql Insert Into in NodeJs

Inserting data into a MySQL database using Node.js is super simple! Here's how to do it using both mysql and mysql2.


✅ Step 1: Install MySQL Package

Choose one of these:

bash

npm install mysql const mysql = require('mysql');const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'myDatabase'});connection.connect((err) => { const mysql = require('mysql2/promise');async function insertUser() { const connection = await mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'myDatabase' }); const sql = 'INSERT INTO users (name, email, age) VALUES (?, ?, ?)'; const values = ['Bob', 'bob@example.com', 30]; const [result] = await connection.execute(sql, values); console.log('Record inserted! ID:', result.insertId); await connection.end();}insertUser();


🧠 Bonus: Insert Multiple Rows at Once

js

const sql = 'INSERT INTO users (name, email, age) VALUES ?';const values = [ ['Tom', 'tom@example.com', 28], ['Jerry', 'jerry@example.com', 24]];connection.query(sql, [values], (err, result) => { if (err) throw err; console.log('Inserted rows:', result.affectedRows);});


🧪 Table Example (users)

sql

CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), email VARCHAR(255), age INT);

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql