Using MySQL Database

Learn how to use the MySQL database.

MySQL database setup

There are many ways to set up the MySQL database.

Use MySQL database on a local machine

The MySQL database server can be installed on a local machine directly, depending on the operating system. For Windows users, there are alternatives, like using XAMPP, Laragon, and other local servers that include the MySQL database server.

To install the MySQL database server, be sure to check the MySQL downloads page. After the MySQL database server is installed, run the server and create a new database with the following query.

CREATE DATABASE inventory;

The database is ready to use with the application.

Use MySQL Database with Docker

The MySQL database is also available on the Docker platform. The Docker image that’s used is ``mariadb, which is an enhanced version of the MySQL database.

First, we ensure Docker is installed, then we pull the mariadb image from the Docker Hub. The following command pulls the mariadb image with the latest version:

docker pull mariadb

Then, we create a container called some-mariadb that uses mariadb as an image to run the MariaDB server.

docker run -itd --name some-mariadb -v /your/volume/mariadb-volume:/var/lib/mysql -e MARIADB_ROOT_PASSWORD=password -p 3306:3306 mariadb:latest

In the commands above, the mariadb container is created to run the MariaDB server. The command uses the following arguments:

  1. -itd means the container is created with interactive and TTY mode (marked with it). The container is detached (marked with d).
  2. --name means the container is created with a specific name. In this command, the name of the container is some-mariadb.
  3. -v means the container is created with the volume to ensure the storage in MariaDB is persistent. If the container is stopped, the data inside the server still exists. The local storage is mapped in /your/volume/mariadb-volume to the container storage in /var/lib/mysql.
  4. -e means the container is created with an environment variable. In this command, the password for the root user is specified.
  5. -p means the container must be exposed to the local network with port 3306. This port is mapped into the container port that uses 3306.
  6. mariadb:latest means the container uses mariadb:latest as the image.

Next, we execute this command to use the MariaDB server inside the container that has already been created. We also enter the password that was specified in the previous command.

docker exec -it some-mariadb mysql -u root -p

Next, we create the new database with the following query:

CREATE DATABASE inventory;

Then, we exit from the MariaDB server with the following command:

EXIT

The database is now ready to use with the application.

Note: To stop the MariaDB server, use docker container stop some-mariadb.

To start the MariaDB server, use docker container start some-mariadb.

Get hands-on with 1400+ tech skills courses.