การดู : 0

04/03/2026 08:45น.

JS2GO EP.44 การเชื่อมต่อ Database: SQL & NoSQL ใน JavaScript และ Go

JS2GO EP.44 การเชื่อมต่อ Database: SQL & NoSQL ใน JavaScript และ Go

#Node.js

#PostgreSQL

#JavaScript

#Database

#Go

#การเชื่อมต่อฐานข้อมูล

การเชื่อมต่อฐานข้อมูล (Database Connection) คือหัวใจของ Backend ทุกระบบ ไม่ว่าจะเป็น API, Microservices, Real-time Server หรือระบบ Enterprise

 

ใน EP.44 นี้ เราจะสรุปอย่างครบเครื่อง:

Databases ที่ครอบคลุม

  • PostgreSQL
  • MySQL
  • MongoDB (NoSQL)
  • Redis (In-memory / Cache)

 

ภาษา & Framework ที่ใช้

  • Node.js (Express)
  • Go (Fiber)

 

สิ่งสำคัญระดับ Production

  • Connection Pooling
  • ORM / Query Builder ที่ควรใช้
  • Timeout / Retry / Circuit Breaker
  • การป้องกัน Connection Leak
  • Health Check และ Monitoring

 

บทความนี้ถูกออกแบบมาให้ อ่านง่าย พร้อมใช้จริงใน Production ไม่ใช่แค่โค้ดตัวอย่าง แต่เป็น “แนวทางที่ใช้จริงในโปรเจกต์ใหญ่”

 

⭐ 1) การเชื่อมต่อ SQL Database (PostgreSQL / MySQL)

 

ฐานข้อมูล SQL เป็นแกนหลักของระบบส่วนใหญ่ โดย PostgreSQL และ MySQL คือสองตัวเลือกยอดนิยมที่สุด

 

🟦 Go (Fiber) → PostgreSQL ด้วย pgx (แนะนำที่สุด)

 

pgx คือ PostgreSQL driver ที่เร็วสุดใน Go รองรับ connection pooling, cancellation, timeout และ statement cache ในตัว

 

➤ Connect Database

import (
	"context"
	"github.com/jackc/pgx/v5/pgxpool"
	"log"
)

var DB *pgxpool.Pool

func ConnectDB() {
	connStr := "postgres://user:password@localhost:5432/mydb"

	pool, err := pgxpool.New(context.Background(), connStr)
	if err != nil {
		log.Fatal("❌ Unable to connect to database:", err)
	}

	DB = pool
	log.Println("✅ Connected to PostgreSQL")
}

 

➤ Query ใน Fiber Handler

func GetUsers(c *fiber.Ctx) error {
	rows, err := DB.Query(context.Background(), "SELECT id, name FROM users")
	if err != nil {
		return c.Status(500).SendString("DB Error")
	}
	defer rows.Close()

	var users []User

	for rows.Next() {
		var u User
		if err := rows.Scan(&u.ID, &u.Name); err != nil {
			return c.Status(500).SendString("Scan error")
		}
		users = append(users, u)
	}

	return c.JSON(users)
}

 

✔ จุดแข็งของ Go + pgx

  • ความเร็วสูงสุดใน ecosystem Go
  • ใช้ Memory ต่ำ
  • รองรับ high concurrency
  • Connection leak เกิดขึ้นยากหากใช้งานถูกต้อง

 

🟧 Node.js (Express) → PostgreSQL ผ่าน pg

 

ไลบรารีมาตรฐานที่ใช้งานได้ดี มี connection pool ในตัว

 

➤ Connect Database

const { Pool } = require("pg");

const pool = new Pool({
  connectionString: "postgres://user:password@localhost:5432/mydb",
});

 

➤ Query

app.get("/users", async (req, res) => {
  try {
    const result = await pool.query("SELECT id, name FROM users");
    res.json(result.rows);
  } catch (err) {
    res.status(500).send("DB Error");
  }
});

 

⭐ 2) เชื่อมต่อ MySQL

 

🟦 Go → MySQL ด้วย go-sql-driver/mysql

import "database/sql"
import _ "github.com/go-sql-driver/mysql"

db, err := sql.Open("mysql", "user:password@tcp(localhost:3306)/mydb")

 

🟧 Node.js → MySQL2 (แนะนำ)

import mysql from "mysql2/promise";

const pool = mysql.createPool({
  host: "localhost",
  user: "root",
  database: "mydb",
});

 

⭐ 3) เชื่อมต่อ MongoDB (NoSQL)

 

เหมาะกับระบบที่ไม่ต้องการ schema ตายตัว หรือเก็บข้อมูลจำนวนมาก

 

🟦 Go → MongoDB (mongo-driver)

client, err := mongo.Connect(context.Background(),
  options.Client().ApplyURI("mongodb://localhost:27017"),
)
collection := client.Database("mydb").Collection("users")

 

🟧 Node.js → MongoDB ด้วย Mongoose (นิยมที่สุด)

import mongoose from "mongoose";

mongoose.connect("mongodb://localhost:27017/mydb");

const User = mongoose.model("User", new mongoose.Schema({
  name: String
}));

 

⭐ 4) เชื่อมต่อ Redis (Cache / Queue / PubSub / Rate limit)

 

🟦 Go → Redis (go-redis v9)

import "github.com/redis/go-redis/v9"

rdb := redis.NewClient(&redis.Options{
  Addr: "localhost:6379",
})

rdb.Set(ctx, "key", "value", 0)

 

🟧 Node.js → Redis (ioredis)

import Redis from "ioredis";

const redis = new Redis();
await redis.set("key", "value");

 

⭐ 5) ORM / Query Builder ที่ควรใช้ (Go / JS)

 

🟦 Go ORMs / Query Builders

Libจุดเด่น
GORMใช้ง่ายที่สุด อ่านง่าย
SQLCgenerate โค้ด compile-time type-safe
Entschema-first ลด human error
pgxเร็วที่สุด เหมาะกับ raw query

 

คำแนะนำ

  • เน้น performance → pgx
  • เน้น type-safe → SQLC
  • เน้นเขียนง่าย → GORM

 

🟧 Node.js ORMs / Query Builders

Libจุดเด่น
Prismatype-safe สุด ง่ายสุด
SequelizeORM รุ่นคลาสสิก ใช้กันมานาน
TypeORMดีมากใน NestJS
Knex.jsQuery Builder ที่เบาและลื่นสุด

 

คำแนะนำ

  • เน้น type-safe → Prisma
  • เน้น performance → Knex.js

 

⭐ 6) Connection Pool เรื่องสำคัญที่สุด!

 

🟦 Go → pgx pool config

poolConfig, _ := pgxpool.ParseConfig(connStr)
poolConfig.MaxConns = 20
poolConfig.MinConns = 5
poolConfig.MaxConnIdleTime = 30 * time.Second

 

🟧 Node.js → pg pool

const pool = new Pool({
  max: 20,
  idleTimeoutMillis: 30000,
  connectionTimeoutMillis: 2000,
});

 

สิ่งที่พบบ่อยที่สุด และควรหลีกเลี่ยง
❌ ห้ามเปิด connection ใหม่ทุกครั้งใน handler
❌ ห้ามเก็บ connection pool ไว้ใน global ที่ scale ไม่ได้
✔ ใช้ connection pool และ inject ให้ service ใช้แทน

 

⭐ 7) Best Practices สำหรับ Production

 

✔ ตั้งค่า Timeout ทุก query

ป้องกัน query ค้าง (long-running query)

 

✔ เปิด Slow Query Logs

ช่วยจับ bottleneck

 

✔ ใช้ Retry + Circuit Breaker

ป้องกันระบบล้มแบบ domino effect

 

✔ Health Check /health/db

เช่น SELECT 1

 

✔ แยก Write / Read

เหมาะกับระบบที่มี traffic เยอะ เช่น e-commerce

 

✔ ใช้ Connection Pool อย่างมีสติ

ค่าสูงเกิน = DB overload
ค่าต่ำเกิน = API ช้า

 


 

📌 สรุป

 

การเชื่อมต่อ Database เป็นทักษะสำคัญที่ JS Dev ต้องมี และ Go Dev ต้องเข้าใจลึก

 

หากตั้งค่าถูกต้อง คุณจะได้ระบบที่:

🚀 เร็ว
🧱 เสถียร
🔐 ปลอดภัย
🌐 พร้อมใช้งาน Production

 

ทั้ง Node.js และ Go มี ecosystem ที่แข็งแรงมาก:

➡ Node.js: pg, Prisma, ioredis
➡ Go: pgx, SQLC, GORM, go-redis

 

เข้าใจเครื่องมือเหล่านี้ = คุณพัฒนาระบบได้ระดับมืออาชีพ

 

🔵 ตอนต่อไป EP.45 การจัดการ Transactions และ ACID ใน Go กับ JavaScript

 

คุณจะได้เรียนรู้ทั้งรูปแบบ SQL Transaction + Business Transaction:

✔ BEGIN / COMMIT / ROLLBACK
✔ ACID Properties
✔ Handling Deadlocks
✔ Transaction Scopes
✔ Go pgx/GORM transaction pattern
✔ Node.js PostgreSQL transaction flow

 

เตรียมพร้อมขึ้นสู่ระดับ Intermediate → Advanced 🌟