Где хранятся базы данных mysql windows

MySQL database files can typically be found in the designated data directory of the MySQL installation. The location of the data directory may vary depending on the operating system and the method used for installation.

On Unix-like systems, such as Linux, macOS, or BSD, you can often find the MySQL data directory at /var/lib/mysql. However, it can be different based on the specific distribution and configuration. In some cases, it may be located at /usr/local/mysql/data or /usr/local/var/mysql.

On Windows, the MySQL data directory is often located at C:\ProgramData\MySQL\MySQL Server X.X\data, where «X.X» represents the version number of MySQL. However, this path may differ if you chose a custom installation location during setup.

It’s worth noting that the data directory contains multiple files and folders which collectively constitute the MySQL database. The primary files you will find include the .frm files (table format files) that store table definitions, the .ibd files (InnoDB) which store data and indexes, the .myd files (MyISAM) which represent MyISAM table data, and the .myi files (MyISAM) which contain MyISAM table indexes.

Remember that modifying or moving these files manually can lead to potential data corruption or loss. Therefore, it’s recommended to use built-in MySQL tools or utilities to handle the database files.

Best MySQL Managed Hosting Providers in 2025




1


Rating is 5 out of 5

Vultr

  • Ultra-fast Intel Core

  • High Performance and Cheap Cloud Dedicated Servers

  • 1 click install WordPress

  • Low Price and High Quality




2


Digital Ocean

Rating is 4.9 out of 5

Digital Ocean

  • Active Digital Community

  • Simple Control Panel

  • Starting from 5$ per month

How can I search for MySQL database files on Linux?

To search for MySQL database files on Linux, you can use the find command with the appropriate search criteria. Here’s how you can do it:

  1. Open a terminal on your Linux machine.
  2. Use the following command to search for files with the .frm extension, which are typically MySQL database table definition files:
1
sudo find / -type f -name "*.frm"

This command will start searching from the root directory (/) and look for files with the .frm extension (-name "*.frm"). The sudo command is used to search in all directories, including those that require administrative privileges.

  1. If you want to search for other MySQL related files like data files (.ibd), configuration files (my.cnf), or log files, you can modify the command accordingly. Here are some examples:
1
2
3
sudo find / -type f -name "*.ibd"   # search for InnoDB data files
sudo find / -type f -name "my.cnf"   # search for MySQL configuration files
sudo find / -type f -name "*.log"   # search for MySQL log files

Remember, searching the entire filesystem can be time-consuming, so be patient, and it’s advisable to narrow down the search path if possible.

Can I delete MySQL database files without affecting the database?

No, deleting MySQL database files without proper backup or restoration procedures can result in permanent data loss. Deleting the database files will remove both the data and metadata associated with the database, rendering the database inaccessible and irrecoverable. It is always important to backup your databases before making any changes to ensure data integrity and to have a restore point in case of mistakes or unforeseen issues.

What are some common file extensions for MySQL database files?

Some common file extensions for MySQL database files include:

  • .frm: File that contains the table definition and structure
  • .ibd: InnoDB table data file
  • .myd: MyISAM table data file
  • .myi: MyISAM table index file
  • .ibd: InnoDB tablespace data file
  • .frm: Archive log file
  • .log: Binary log file
  • .sql: SQL script file
  • .sql.gz: Compressed SQL backup file
  • .dump: MySQL dump file

Best MySQL Database Books to Read in 2025




1


Rating is 5 out of 5

Murach’s MySQL (3rd Edition)




2


Rating is 4.9 out of 5

Learning MySQL: Get a Handle on Your Data




3


Rating is 4.8 out of 5

MySQL Crash Course: A Hands-on Introduction to Database Development




4


Rating is 4.7 out of 5

PHP & MySQL: Server-side Web Development




5


Rating is 4.6 out of 5

MySQL Cookbook: Solutions for Database Developers and Administrators




6


Rating is 4.5 out of 5

The MySQL Workshop: A practical guide to working with data and managing databases with MySQL




7


Rating is 4.4 out of 5

Murach’s PHP and MySQL (4th Edition)




8


Rating is 4.3 out of 5

High Performance MySQL: Proven Strategies for Operating at Scale




9


Rating is 4.2 out of 5

MySQL(TM): The Complete Reference

How can I copy MySQL database files to a different server?

To copy MySQL database files to a different server, you can follow these general steps:

  1. Export the database: Use the mysqldump command to create a backup of the database on the source server. For example, run the following command in the terminal:
1
mysqldump -u <username> -p<password> <database_name> > <backup_file.sql>

Replace <username>, <password>, <database_name>, and <backup_file.sql> with the appropriate values.

  1. Transfer the backup file: Use a secure file transfer method (e.g., SCP, SFTP) to transfer the backup file to the destination server. You can use a tool like WinSCP, FileZilla, or the SCP command.
  2. Import the database: On the destination server, import the backup file into a new database using the mysql command. Run the following command in the terminal:
1
mysql -u <username> -p<password> <database_name> < <backup_file.sql>

Replace <username>, <password>, <database_name>, and <backup_file.sql> with the appropriate values.

  1. Verify the database: Log in to the destination server’s MySQL shell using the appropriate credentials and check if the copied database is present. Run the following command:
1
mysql -u <username> -p<password>

Then, within the MySQL shell, list the databases:

If you see the transferred database in the list, the copying process was successful.

Note: This approach assumes you have the necessary privileges on both the source and destination servers. If you have access to a database management tool like phpMyAdmin or Adminer, you can also use them to export and import the database directly.

How can I backup MySQL database files?

There are a few different methods to backup MySQL database files:

  1. Using mysqldump:
  • One of the most common methods is to use the mysqldump utility provided with MySQL.
  • Open a command prompt or terminal and run the following command:
    mysqldump -u username -p database_name > backup.sql
    Replace username with your MySQL username, database_name with the name of the database you want to backup, and backup.sql with the desired name for the backup file.
  • Enter your MySQL password when prompted, and the specified database will be exported to a SQL file.
  1. Using the MySQL Workbench:
  • If you have MySQL Workbench installed, you can use the Backup feature to create database backups.
  • Open MySQL Workbench and connect to your MySQL server.
  • From the top menu, go to Server > Data Export.
  • Select the database(s) you want to backup, choose an output folder, and click Start Export.
  1. Copying the raw database files:
  • Shutdown the MySQL server if it is running.
  • Locate the data directory where your MySQL installation stores the database files. The default location on Linux is typically /var/lib/mysql/, but this might vary depending on your operating system.
  • Copy the entire data directory or individual database folders to a backup location. This method provides a complete backup, including all the database files, but it requires shutting down the MySQL server.

It is recommended to use the mysqldump method or MySQL Workbench backup feature as they provide more consistent and reliable backups.

Last updated on September 11th, 2020 at 11:44 am

You can find MySQL database location on your hard disk in the following ways:

MySQL database location in Windows

1) Locate the my.ini file, which store in the MySQL installation folder.

For Example,

C:\Program Files\MySQL\MySQL Server 5.5\my.ini

2) Open the “my.ini” with notepad.

#Path to the database root
datadir="C:/Documents and Settings/All Users/Application Data/MySQL/MySQL Server 5.1/Data/"

Find the “datadir” variable. It’s value is the MySQL database location in Windows.

MySQL database location in Linux / Mac

1) Locate the my.cnf with the find / -name my.cnf command.

$ find / -name my.cnf
/etc/mysql/my.cnf

2) View the my.cnf file

$ cat /etc/mysql/my.cnf

[mysqld]

user = mysql pid-file = /var/run/mysqld/mysqld.pid socket = /var/run/mysqld/mysqld.sock port = 3306 basedir = /usr datadir = /var/lib/mysql tmpdir = /tmp language = /usr/share/mysql/english skip-external-locking

3) Find the “datadir” variable. It’s value is MySQL database location in Linux/Mac.

You can change the value of this variable and restart the server to change MySQL database location. You will need to copy the existing database files from old to new location. Only then they will continue to work.

Related posts:

Sreeram Sreenivasan is the Founder of Ubiq. He has helped many Fortune 500 companies in the areas of BI & software development.

Skip to content

Summary: in this tutorial, you will learn about MySQL data directory. We’ll cover its default location, and configuration, and share some best practices for effective management.

Introduction to MySQL Data Directory

MySQL data directory stores the databases, tables, log files, and other essential elements that enable the functioning of the MySQL Server.

Default location

When installing MySQL, you can explicitly set the location for the data directory.

If you use the default, the data directory location depends on the operating system where you install MySQL Server as illustrated in the following table:

OS Path
Linux /var/lib/mysql/
Windows C:\ProgramData\MySQL\MySQL Server{version}\Data
macOS /usr/local/mysql/data/

Configuration File

MySQL stores the location of the data directory in the MySQL configuration file (my.cnf or my.ini). For example:

[mysqld]
datadir=/var/lib/mysql/Code language: JavaScript (javascript)

To check the current location of the data directory using the mysql program, you can follow these steps:

First, connect to the MySQL Server:

mysql -u root -p

Second, display the value of the @@datadir system variable:

SELECT @@datadir;Code language: CSS (css)

Here’s the output on Linux and macOS:

+-----------------+
| @@datadir       |
+-----------------+
| /var/lib/mysql/ |
+-----------------+
1 row in set (0.00 sec)Code language: JavaScript (javascript)

The output on Windows will look like this:

+---------------------------------------------+
| @@datadir                                   |
+---------------------------------------------+
| C:\ProgramData\MySQL\MySQL Server 8.0\Data\ |
+---------------------------------------------+
1 row in set (0.00 sec)Code language: JavaScript (javascript)

Contents

The following are the contents of the data directory:

  • Databases: MySQL stores each database in a separate subdirectory within the data directory.
  • Tables: MySQL stores tables and their associated data files within the respective database directories.
  • Log Files: MySQL uses various log files (e.g., error log, binary log) to record events and transactions.
  • Temporary Files: The tmp directory manages temporary tables and other temporary storage requirements.

Security

Typically, when setting up MySQL, the MySQL installer creates a user called mysql and assigns its home directory to the data directory, commonly found at /var/lib/mysql/.

The mysql user is granted the appropriate permissions to access the directories and files in the data directory.

Summary

  • MySQL data directory is an important directory that stores databases, tables, log files, and other essential data for the MySQL database server.

Was this tutorial helpful?

От автора: а что это вы под ногами ищете? Базу данных? Поверьте, скорее все, она никуда не делась, и лежит «целехонькая» на вашем ПК или сервере! Там уже смотрели? Наверное, вы просто не знаете, где хранятся данные MySQL. Об этом мы вам сегодня и расскажем.

Импорт-экспорт данных в MySQL

Чаще всего найти утерянные базы данных нужно для импорта или копирования. К счастью, для этого не обязательно знать место их «дислокации» на дисковом пространстве. Программные интерфейсы для работы с СУБД MySQL имеют встроенные средства переноса и создания копий БД и таблиц.

В наших «широтах» самой востребованной остается оболочка phpMyAdmin, предназначенная для администрирования системы управления БД MySQL. На примере этого веб-приложения мы и рассмотрим встроенные средства, которые позволят нам остаться в неведении, где находится MySQL.

В phpMyAdmin создание копий баз данных происходит через вкладку «Экспорт». Для дублирования БД или таблицы слева в списке выберете нужный для копирования элемент. После этого перейдите в раздел «Экспорт». В окне параметров в подразделе «Способ экспорта» должно быть установлено значение «Обычный». Затем в списке выделите базу данных (таблицу). После чего нажимаете в самом низу окна «Ок».

В результате программа создаст копию и сохранит ее на клиентской стороне. Вся работа с веб-приложением происходит через браузер, поэтому созданный дубликат БД нужно искать в папке загрузок.

Место хранения оригиналов баз

Знание встроенного функционала phpMyAdmin поможет быстро создать копии нужных данных. Но если на компьютере не установлена ни одна из программных оболочек для администрирования СУБД. А вам нужно перенести БД на другой сервер. Или изменить хранящуюся в таблицах информацию. При этом выполнять запросы придется через консоль, где обязательно прописывается путь к БД. Как видите знать, где хранится база данных MySQL, важно и нужно.

Вот еще один пример «из жизни начинающего админа». Предположим, первоначально вы пользовались Denwer. Но в один «непогожий» день вы нечаянно удалили часть файлов локального сервера. В результате чего он больше не запускается, и вы начинаете «рыть» оставшиеся папки в надежде спасти хотя бы базы данных. Но в этом случает также «удобнее» знать, где копать. Вот пример пути, где в веб-сервере хранятся БД: F:\Webserver\usr\local\mysql-5.5\data, где F – это диск, на котором был установлен Denwer.

Для открытия файлов скопированных БД потребуется phpMyAdmin. Если вы установили сервер СУБД без оболочки, тогда по умолчанию место, где хранятся базы данных MySQL, находится здесь: C:\Documents and Settings\All Users\Application Data\MySQL\MySQL Server 5.1\data

Файл my.ini

Все описанные методы связаны с осуществлением поиска (в зависимости от варианта использования СУБД) той или иной папки, в которой программы (или сервер) сохраняют созданные базы. Но неужели пользователь никак не может повлиять на это, и самостоятельно указать место на дисковом пространстве MySQL, где хранятся все БД.

Такой вариант настройки был предусмотрен создателями этой системы управления. Все основные параметры задаются в файле my.ini. Он расположен в той же директории, куда установлена и система СУБД.

Данный тип файлов относится к конфигурационным, и открывается с помощью обычного «Блокнота». Чтобы задать «свое» место для всех созданным БД, откройте файл my.ini. Затем найдите в нем раздел [mysqld], и в параметре datadir пропишите путь к нужной папке. После сохранения внесенных изменений (Файл> Сохранить) все существующие базы будут перенесены в указанное вами место файловой системы компьютера или сервера.

Средства SQL

Все описанные выше варианты узнать в MySQL, где лежит БД, являются второстепенными. Потому что СУБД не понимает человеческой речи и письменности. Для общения с ней существует специальный язык SQL. Аббревиатура переводится как язык структурированных запросов (structured query language). То есть с помощью операторов и команд этого языка можно влиять на структуру содержащейся в источнике информации: делать выборки, обновлять данные, вставлять или удалять.

Но не будем слишком забираться в «дремучий лес» профессиональных знаний, нас интересует единственная команда SHOW. Точнее, один из ее вариантов SHOW VARIABLES. Эта команда SQL используется в администрировании для получения служебной информации о конкретном сервере или базе.

SHOW VARIABLES выводит список переменных и их значений из INFORMATION_SCHEMA, которая представляет собой «служебную» БД, в которой содержится информация обо всех базах, подключенных к серверу. Пример запроса: SHOW VARIABLES;

Но из всего этого списка нас интересует лишь одна переменная, с помощью которой можно «узнать» у сервера MySQL, где хранится база. Это переменная basedir, в значение которой записан путь к основной директории. Пример запроса: SHOW VARIABLES LIKE ‘basedir’;

А сейчас прекращайте понапрасну «рыться» в файловой системе своего ПК. Теперь вы точно знаете, как правильно «спросить» у СУБД MySQL, где хранятся базы. Надеемся, нам удалось научить вас этому!

Обновлено:
Опубликовано:

Тематические термины: MySQL, MariaDB, Linux.

В статье пойдет речь о просмотре и смене пути расположения файлов баз данных MySQL. Приведенные примеры выполнены на CentOS 7 — также они будут работать на Ubuntu и многих других дистрибутивах Linux, FreeBSD и Windows.

Просмотр путей
    Командная строка
    Оболочка MySQL
    phpMyAdmin
Смена расположения баз
Смотрите также

Посмотреть текущий путь

Увидеть, где хранятся базы можно несколькими способами. 

Способ 1. Командная строка Linux.

В командной строке вводим:

systemctl status mysql || systemctl status mariadb

* для Windows используем оснастку Службы. Для FreeBSD используем команду service mysql-server stop.

Пример ответа:

mariadb.service — MariaDB database server
   Loaded: loaded (/usr/lib/systemd/system/mariadb.service; enabled; vendor preset: disabled)
   Active: active (running) since Ср 2018-07-11 15:38:16 MSK; 23h ago
  Process: 1067 ExecStartPost=/usr/libexec/mariadb-wait-ready $MAINPID (code=exited, status=0/SUCCESS)
  Process: 992 ExecStartPre=/usr/libexec/mariadb-prepare-db-dir %n (code=exited, status=0/SUCCESS)
 Main PID: 1066 (mysqld_safe)
   CGroup: /system.slice/mariadb.service
           ??1066 /bin/sh /usr/bin/mysqld_safe —basedir=/usr
           ??1248 /usr/libexec/mysqld —basedir=/usr —datadir=/var/lib/mysql —plugin-dir=/usr/lib64/mysql/plugin —log-error=/var/log/mariadb/mariadb.log —pid-file=/var/run/mariadb/mariadb.pid —socket…

* в выделенном фрагменте /var/lib/mysql — путь до файлов базы данных.

Способ 2. Командная оболочка MySQL.

Данный способ является более универсальным — он подойдет для любого дистрибутива Linux, FreeBSD, Windows. Также, метод универсален с точки зрения метода установки MySQL — чистая установка или в составе готовой сборки (Open Server, Xampp, Denwer …).

Заходим под пользователем root в командную оболочку СУБД:

mysql -uroot -p

Вводим:

> SHOW VARIABLES WHERE Variable_Name LIKE «datadir»;

или

> select @@datadir;

Пример ответа:

+—————+——————+
| Variable_name | Value           |
+—————+——————+
| datadir       | /var/lib/mysql/ |
+—————+——————+

Способ 3. Через phpMyAdmin.

Если у нас нет доступа к серверу по SSH или удаленному рабочему столу, запрос можно сделать в phpMyAdmin:

Пример создания запроса на получение пути к базе MySQL в phpMyAdmin

Смена пути

Останавливаем сервер баз данных:

systemctl stop mysql || systemctl stop mariadb

Создаем новый каталог, например:

mkdir /home/mysql

Переносим содержимое старого каталога в новый:

mv /var/lib/mysql/* /home/mysql/

Задаем права и владельца для нового каталога:

chown mysql:mysql /home/mysql

chmod 755 /home/mysql

Открываем конфигурационный файл my.cnf:

vi /etc/my.cnf.d/server.cnf

* в разных версиях mysql и mariadb могут использоваться разные пути:

  • /etc/my.cnf.
  • /etc/my.cnf.d/server.cnf.
  • /etc/my.cnf.d/mariadb-server.cnf.
  • В Windows это my.ini.

и задаем новый путь:

[mysqld]
datadir = /home/mysql

Запускаем сервер:

systemctl start mysql || systemctl start mariadb

Смотрите также

Установка MariaDB на CentOS 7

Как восстановить базу MySQL

Создание и удаление баз в MySQL/MariaDB

Экспорт баз данных MariaDB/MySQL в phpMyAdmin

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Network manager для windows
  • Регистрация windows 10 kms
  • Как отключить активацию windows 10 pro навсегда
  • Нет доступа к общему принтеру windows 10
  • Ошибка windows script host не удается найти файл сценария 1 vbs