discord-hosting.cloud
20% Off First MonthSee prices

Guide

Databases for Discord bots: SQLite or MySQL

Most bots need to remember something: per-server settings, levels, warnings, an economy. A SQLite file is enough for a single bot process; a MySQL database is better when several processes (shards) or tools share the data.

Updated 6 min read

SQLite: a file next to your bot

Good for small and medium bots in one process. The database is a file in your server's folder, so it is included in your backups.

// npm install better-sqlite3
import Database from 'better-sqlite3';
const db = new Database('data.db');
db.exec('CREATE TABLE IF NOT EXISTS prefixes (guild TEXT PRIMARY KEY, prefix TEXT)');
db.prepare('INSERT OR REPLACE INTO prefixes VALUES (?, ?)').run(guildId, '!');

MySQL: a database from the panel

  1. 1Create the database

    Open Databases for your bot server and create one. The panel shows the host, port, database name, user and password. Every plan includes MySQL databases (the number depends on the plan).

  2. 2Store the details in .env

    Never put the password in your code.

    DB_HOST=203.0.113.20
    DB_PORT=3306
    DB_NAME=s123_bot
    DB_USER=u123_abcdef
    DB_PASS=from-the-panel
  3. 3Connect

    Use a connection pool so the bot reconnects on its own.

    // Node.js: npm install mysql2
    import mysql from 'mysql2/promise';
    const pool = mysql.createPool({ host: process.env.DB_HOST, port: Number(process.env.DB_PORT), user: process.env.DB_USER, password: process.env.DB_PASS, database: process.env.DB_NAME });
    const [rows] = await pool.query('SELECT 1');
    
    # Python: pip install aiomysql
    pool = await aiomysql.create_pool(host=os.environ['DB_HOST'], port=int(os.environ['DB_PORT']), user=os.environ['DB_USER'], password=os.environ['DB_PASS'], db=os.environ['DB_NAME'])

Back up your data

Create backups from Backups before big changes; SQLite files are part of them. For MySQL, export a dump from time to time (for example with mysqldump from your computer) and keep a copy off the server.