NEW 📢 Black Friday: our launch offer ends 30 Nov. Up to 70% off your first month on every game!See plans
Black FridayUp to 70% off your first month, ends 30 NovEnds in 9d 02h 53mBlack FridayUp to 70% off your first month, ends 30 NovEnds in 9d 02h 53mBlack FridayUp to 70% off your first month, ends 30 NovEnds in 9d 02h 53m

How to use a database with your Discord bot

Discord bot hostingUpdated Nov 6, 20264 min read

Your bot plan includes a MySQL-compatible database. Create it on the Databases page, copy its details into variables on the Bot page, pane Environment, and read them in your code. The password then never sits in a file.

1. Create the database

  1. Open your bot server in the panel and click Databases in the menu.
  2. Click New database.
  3. Optionally give it a Label of 3 to 40 letters, numbers or underscores, such as bot_data. Will be created as shows the full name. Click Create database.
  4. Click the database in Your databases. Its Connection card shows Host, Port, Database, Username and Password, each with a copy button. The Ready-made config card below has the same details ready to paste: pick Node.js (mysql2), Python (aiomysql), JDBC URL or Generic URL under Config for.

A database's page, Connect section: the Connection card with Host, Port, Database, Username and Password, and the Ready-made config card below.

Your bot server can connect with these details. A desktop tool on your own computer cannot: to look inside the database, use Open in phpMyAdmin. The full page: How to use databases with your server.

2. Put the details in Environment

  1. Open the Bot page, pane Environment.
  2. Click Paste a .env file and paste five lines with your values:
    DB_HOST=your-host
    DB_PORT=3306
    DB_NAME=your-database
    DB_USER=your-username
    DB_PASSWORD=your-password
  3. The list shows DB_PASSWORD with a Secret badge: names that look like secrets are saved write-only. Click Import 5 variables.
  4. Restart the bot. Variables reach your code the next time it starts.

Use the real port from the database page; 3306 above is only an example. More on this pane: How to set environment variables and secrets.

3. Connect from your code

Node.js (mysql2)

Add mysql2 to package.json, then:

const mysql = require('mysql2/promise');

const pool = mysql.createPool({
  host: process.env.DB_HOST,
  port: Number(process.env.DB_PORT),
  database: process.env.DB_NAME,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  connectionLimit: 5,
});

async function addWarning(userId, reason) {
  await pool.execute('INSERT INTO warnings (user_id, reason) VALUES (?, ?)', [userId, reason]);
}

pool.query('CREATE TABLE IF NOT EXISTS warnings (id INT AUTO_INCREMENT PRIMARY KEY, user_id VARCHAR(32), reason TEXT)');

Python (aiomysql)

Add aiomysql to requirements.txt, then:

import os

import aiomysql


async def make_pool():
    return await aiomysql.create_pool(
        host=os.environ["DB_HOST"],
        port=int(os.environ["DB_PORT"]),
        db=os.environ["DB_NAME"],
        user=os.environ["DB_USER"],
        password=os.environ["DB_PASSWORD"],
        autocommit=True,
    )


async def add_warning(pool, user_id, reason):
    async with pool.acquire() as conn:
        async with conn.cursor() as cur:
            await cur.execute("INSERT INTO warnings (user_id, reason) VALUES (%s, %s)", (user_id, reason))

Create the pool once, for example in discord.py's setup_hook, and reuse it in every command.

Step-by-step guides per library

Good to know

  • Use one connection pool for the whole bot, not a new connection per command.
  • Always pass user input as query parameters (? or %s), never by gluing text into the SQL.
  • Backups do not include databases. Export yours from phpMyAdmin from time to time.
  • Reset password on the database's Connection card makes a new password and breaks the old one at once. Paste the new one into DB_PASSWORD (Replace) and restart the bot.
  • For a small bot, a SQLite file in your server's folder is fine too: no setup, and it is part of your file backups.
  • Access denied means a wrong user or password; ECONNREFUSED or a timeout means a wrong host or port. Compare with the database page.

Already hosting your bot somewhere else? Move it to us

OUR LATEST BLOGS