NEW 📢 Save up to 30% on your first month, limited time offer!

How to use a database with your Discord bot

Discord bot hostingUpdated Oct 6, 20263 min read

A bot that remembers things, such as levels, warnings or settings per server, needs somewhere to keep them. Your bot plan includes one database. You can also use a file such as SQLite, which needs no setup but is harder to share between two bots.

Create the database

  1. Open your server in the panel and click Databases in the left menu.
  2. Click New database, choose the type, add a label such as bot-data and click Create database.
  3. Click the database to see the host, port, database name, user and password. See How to use databases with your server for the full page.

Keep the details out of your code

Put the connection details in a file your code reads, such as .env, and do not commit that file to git. In Files, create .env:

`` DB_HOST=your-host DB_PORT=3306 DB_NAME=your-database DB_USER=your-user DB_PASSWORD=your-password ``

Node.js (mysql2 and dotenv)

Add mysql2 and dotenv to package.json, then:

```js require('dotenv').config(); 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, });

async function main() { await pool.query('CREATE TABLE IF NOT EXISTS warnings (id INT AUTO_INCREMENT PRIMARY KEY, user_id VARCHAR(32), reason TEXT)'); const [rows] = await pool.query('SELECT COUNT(*) AS n FROM warnings'); console.log('warnings stored:', rows[0].n); } main(); ```

Python (aiomysql)

Add aiomysql and python-dotenv to requirements.txt, then:

```python import os import aiomysql from dotenv import load_dotenv

load_dotenv()

async def get_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, ) ```

Good to know

  • Use a connection pool, not a new connection for every command.
  • Always pass user input as query parameters, never by joining text into the SQL.
  • Include the database in your backups: How to create, download and restore backups.
  • If the bot cannot connect, check the host and port against the database page and that the password has no stray space.

CREATE YOUR GAME SERVER
READY TO GET STARTED?

Save up to 30% on your new game server.
Premium performance, instant activation, and unbeatable reliability all at a better price.

OUR LATEST BLOGS