Databases2 minutes to read

How do I save a Discord server’s settings in MySQL?

Keep one configuration row per Discord server in MySQL. Set a welcome channel, update it and check that another server’s settings stay independent.

Use the guild ID as the row key

Store each Discord server’s settings in a MySQL row keyed by its guild ID. When an administrator picks a new welcome channel, insert or update that guild’s row. Two servers can have the same display name. Their distinct guild IDs keep their settings separate.

On Bothosting, MySQL runs as a separate database deployment. Connect with the hostname, assigned port, server certificate and client identity shown in Connection. The application user and database are both named app. Open a test connection with the MySQL client instructions before configuring your bot.

Try a setting in a test database

This small table keeps the identifiers as text, so the bot can pass the strings it receives from Discord directly to the driver. Run the example in an empty test database. The numbers below stand in for a guild and a channel.

Create a test table and save a setting in MySQL 8.4
CREATE TABLE guild_settings (
  guild_id VARCHAR(32) PRIMARY KEY,
  welcome_channel_id VARCHAR(32) NOT NULL
);

INSERT INTO guild_settings (guild_id, welcome_channel_id)
VALUES ('10001', '20001') AS incoming
ON DUPLICATE KEY UPDATE welcome_channel_id = incoming.welcome_channel_id;

Run only the INSERT again, changing the channel to 20002. The primary key makes the second call update the existing row. In the bot’s command handler, check the member’s permission to change server settings and use bound driver parameters for those two values. MySQL’s insert-or-update syntax.

Test two servers and a restart

Query SELECT welcome_channel_id FROM guild_settings WHERE guild_id = '10001'. Expect one row containing 20002. Insert a different guild ID and channel, then query the first ID again. Finally, restart the bot and ask it to show the saved channel in each test guild. That checks database persistence, the bot’s connection and the guild ID your handler takes from the interaction.

Allow memory and a deployment slot for each process. A minimum MySQL instance uses all the memory on Relay. Account for the bot too when comparing database hosting plans.