How to change the directory of the MySQL database?

To change the directory of the MySQL database, follow these steps:

  1. Stop the MySQL service.
  2. Copy or move the current database directory to a new location. You can use the cp command to copy the directory, for example: cp -r /var/lib/mysql /new/directory.
  3. Edit the MySQL configuration file. Open the MySQL configuration file my.cnf, which is typically located in /etc/mysql/my.cnf or /etc/my.cnf, depending on the operating system.
  4. “In the configuration file, locate the datadir parameter, which specifies the directory for the MySQL database. Change the value of the datadir parameter to the new database directory path, for example: datadir = /new/directory/mysql.”
  5. Save and close the configuration file.
  6. Change the permissions of the new database directory to ensure MySQL can access it. You can use the chown command to change the owner and group of the directory, for example: sudo chown -R mysql:mysql /new/directory.
  7. Start the MySQL service.
  8. Confirm if MySQL is able to access the new database directory. You can use the statement SHOW VARIABLES LIKE ‘datadir’; to check the current path of the database directory and ensure it has been changed to the new path.

Please make sure to back up the original database directory before performing the above operation to prevent unexpected data loss.

bannerAds