
Mysql Get Started in NodeJs
Getting started with MySQL in Node.js is easy! Here's a complete beginner-friendly guide to help you connect and run queries.
๐ง Step 1: Install MySQL Node Package
Choose one of these:
๐น For basic (callback-based) usage:
npm install mysql
๐น For modern (async/await support):
npm install mysql2
โ Step 2: Create a Connection
๐ app.js
(using mysql
):
const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: '', // your MySQL password database: 'myDatabase' // your database name});// Connectconnection.connect((err) => { if (err) throw err; console.log('Connected to MySQL!'); // Example query connection.query('SELECT NOW()', (err, result) => { if (err) throw err; console.log('Server Time:', result); connection.end(); // close connection });});
โ
Step 2 (ALT): Use mysql2
with Async/Await
const mysql = require('mysql2/promise');async function connectMySQL() { const connection = await mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'myDatabase' }); const [rows] = await connection.execute('SELECT NOW()'); console.log('Server Time:', rows); await connection.end();}connectMySQL();
๐งช Common Operations
Task | Code Snippet Example |
---|---|
Create Database | CREATE DATABASE dbname |
Create Table | CREATE TABLE users (id INT, name VARCHAR(255)) |
Insert Data | INSERT INTO users (name) VALUES ('Alice') |
Select Data | SELECT * FROM users |
Update Data | UPDATE users SET name='Bob' WHERE id=1 |
Delete Data | DELETE FROM users WHERE id=1 |
๐ง Tips
Use
connection.end()
to close the DB connection after you're done.Use
try/catch
for better error handling.Store credentials in
.env
for security in real projects.