Step-by-step code examples for connecting your discord.js bot to MySQL (mysql2) or PostgreSQL (pg) with proper connection pools.
Connecting a discord.js bot to MySQL or PostgreSQL requires installing the correct driver, creating a connection pool, and following security best practices. This guide provides working code examples for both databases.
Install the package:
bashnpm install mysql2 dotenv
Create a db.js module:
javascriptconst mysql = require("mysql2/promise"); require("dotenv").config(); const pool = mysql.createPool({ host: process.env.DB_HOST, user: process.env.DB_USER, password: process.env.DB_PASS, database: process.env.DB_NAME, waitForConnections: true, connectionLimit: 10, queueLimit: 0 }); async function getBalance(userId) { const [rows] = await pool.execute( "SELECT balance FROM users WHERE user_id = ?", [userId] ); return rows[0]?.balance ?? 0; } async function setBalance(userId, amount) { await pool.execute( "INSERT INTO users (user_id, balance) VALUES (?, ?) ON DUPLICATE KEY UPDATE balance = ?", [userId, amount, amount] ); } module.exports = { getBalance, setBalance };
Install the package:
bashnpm install pg dotenv
Create a db.js module:
javascriptconst { Pool } = require("pg"); require("dotenv").config(); const pool = new Pool({ host: process.env.DB_HOST, user: process.env.DB_USER, password: process.env.DB_PASS, database: process.env.DB_NAME, port: 5432 }); async function getBalance(userId) { const res = await pool.query( "SELECT balance FROM users WHERE user_id = $1", [userId] ); return res.rows[0]?.balance ?? 0; } async function setBalance(userId, amount) { await pool.query( "INSERT INTO users (user_id, balance) VALUES ($1, $2) ON CONFLICT (user_id) DO UPDATE SET balance = $2", [userId, amount] ); } module.exports = { getBalance, setBalance };
Add DB_HOST, DB_USER, DB_PASS, and DB_NAME as environment variables in your Pterodactyl Startup tab. They will never appear in your codebase. See Database Hosting to get your credentials.
Explore related hosting tutorials, benchmarks, and deployment guides
High-performance infrastructure built for developers, bot creators, and server owners
24/7 no-sleep bot hosting with Pterodactyl panel, DDoS protection and Node.js/Python support.
Full-root cloud VPS with guaranteed resources, NVMe SSD and DDoS protection.
High-performance Minecraft Java & Bedrock servers with Pterodactyl panel.
High-speed managed MongoDB, PostgreSQL & MySQL databases with automated daily backups.
Managed Lavalink nodes for Discord music bots with ultra-low audio latency.
Run your Telegram bots 24/7 with low-latency servers and affordable INR plans.