Sorry, you have been blocked
This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data.
What can I do to resolve this?
You can email the site owner to let them know you were blocked. Please include what you were doing when this page came up and the Cloudflare Ray ID found at the bottom of this page.
Cloudflare Ray ID: 7a6d3ec6aa882498 • Your IP: Click to reveal 88.135.219.175 • Performance & security by Cloudflare
Как узнать путь до файлов базы данных MySQL/MariaDB в Linux и Windows
Файлы базы MySQL/MariaDB данных хранятся на жёстком диске. По умолчанию это папка data внутри директории исполнимых файлов MySQL (в Windows) или в директории /var/lib/mysql/ (Linux).
В настройках можно указать любое расположение базы данных MySQL — необязательно в папке с установленной программой, это может быть произвольная папка. Более того, на серверах с высокой нагрузкой рекомендуется файлы баз данных выносить на отдельный диск, чтобы не снижалась производительность из-за одновременного доступа к диску для чтения баз данных и для запуска исполнимых файлов.
Иногда непросто разобраться в сложной структуре веб-сервера, иногда нужно в скрипте реализовать возможность определять путь до файлов баз данных — например, в целях настройки автоматического резервного копирования.
Далее будет показано, как в командной строке можно определить, где расположены файлы баз данных MySQL в Windows и в Linux.
Определение пути без подключения к серверу СУБД
В Windows
В ОС Windows для получения пути до базы данных введите команду:
Если вы получите сообщение, что команда mysqld не найдена, значит нужно указать путь до исполнимого файла mysqld или перейти в директорию с исполнимым файлом. Предположим, MySQL/MariaDB установлена в папке C:\Server\bin\mariadb, тогда переходим в поддиректорию bin, содержащую исполнимые файлы, и выполняем там указанную выше команду:
В Linux
В операционной системе Linux выполните следующую команду и она покажет вам путь до базы данных:
Переменная @@datadir;
Этот способ работает на всех системах одинаково. Нужно выполнить подключение к системе управления базой данных. Например, для пользователя root это делается так:
И затем в консоли MySQL/MariaDB выполните:
Как видно на скриншоте, путь до файлов базы данных на сервере, где введена команда, c:\Server\data\DB\data\.
Ещё один вариант выполнения данной команды:
Как узнать настройки директорий в MySQL/MariaDB
Чтобы показать информацию о всех настройках директорий СУБД сервера, выполнит команду:
Пример вывода в Windows для MariaDB:
Чтобы вывести только datadir выполните команду:
Как узнать путь до базы данных MySQL/MariaDB в скрипте
Если вы используете полученное значение пути до папки баз данных, например, в скрипте, то есть вам нужно только значение без лишних символов псевдографики, которая имитирует таблицу, то примените следующую команду:
Примечание: если в Linux у вас проблемы с последними командами, то инвертируйте (поменяйте местами) одинарные и двойные кавычки.
Также не забывайте менять пользователя root на имя вашего пользователя.
Где хранятся базы данных MySQL
Файлы баз данных в СУБД MySQL хранятся на жёстком диске. По умолчанию все файлы с базами хранятся в директории /var/lib/mysql. Однако это путь можно изменить.
В данной статье будет показано как посмотреть, где хранятся файлы баз данных в СУБД MySQL в операционной системе Ubuntu 20.04.
Где хранятся базы данных MySQL
По умолчанию все файлы с базами хранятся в директории /var/lib/mysql. Однако, чтобы убедиться в этом можно выполнить команду sudo grep -R ‘datadir’ /etc/mysql/ которая отобразит полный путь до файлов, в которых хранятся базы данных:
sudo grep -R ‘datadir’ /etc/mysql/
Если перейти по предложенному пути — /var/lib/mysql то в директории будут расположены все необходимые файлы c баз данных. Команду для перехода в директорию необходимо выполнять из-под пользователя root иначе будет ошибка Permission denied:
Теперь вы знаете где находятся базы данных MySQL. Также можно выполнить команду mysqld с параметрами —verbose и —help которая отобразит путь хранения файлов с базами данных. Данная команда аналогична предыдущей команде.
mysqld —verbose —help | grep ^datadir
Если есть необходимость в изменении пути хранения файлов баз данных, то необходимо открыть конфигурационный файл MySQL от имени суперпользователя (root) при помощи любого текстового редактора. В данном примере, как мы узнали выше, конфигурационный файл находится по пути /etc/mysql/mysql.conf.d/mysqld.cnf. Команда для его редактирования будет выглядеть следующим образом:
sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf
В открывшемся файле необходимо найти блок [mysqld] и в нем параметр с именем datadir в котором можно пописать нужный путь, где будут храниться базы данных. После того как путь был задан необходимо сохранить изменения, закрыть текстовый редактор и перезапустить СУБД при помощи команды:
sudo systemctl restart mysql
Выводы
В данной короткой статье было рассмотрено, где хранятся базы данных в СУБД MySQL. Также при желании можно изменить директорию для хранения. Есть ли у вас опты работы с СУБД MySQL? Расскажите в комментариях!
Where does MySQL store database files on Windows and what are the names of the files?
I accidentally formatted my hard drive and re-installed Windows and forgot to backup an important database I had in my MySQL server. I’m trying to salvage files now using some software, but I don’t know what to look for.
What is the path that the files are stored in, and what are the files named (what naming convention, or file extension should I look for)?
I believe my server was using MyISAM, but not 100% sure.
13 Answers 13
You can check my.ini file to see where the data folder is located.
Usually there is a folder
MySQL data storage:
The *.frm files contain the table definitions. Your *.myi files are MyISAM index files. Your *.myd files contain the table data.
Edit/Update. Because of the interest shown in the question here is more info which is found also in the comments.
In Windows 8.1, the MySQL databases are stored (by default) here: C:\ProgramData\MySQL\MySQL Server 5.6\data
The folder C:\ProgramData is a hidden folder, so you must type it into Windows Explorer address to get there. In that data folder, the databases are named /
Thank @marty-mcgee for this content
In Windows 7, the MySQL database is stored at
C:\ProgramData\MySQL\MySQL Server 5.6\data
Note: this is a hidden folder. And my example is for MySQL Server version 5.6; change the folder name based on your version if different.
It comes in handy to know this location because sometimes the MySQL Workbench fails to drop schemas (or import databases). This is mostly due to the presence of files in the db folders that for some reason could not be removed in an earlier process by the Workbench. Remove the files using Windows Explorer and try again (dropping, importing), your problem should be solved.
I have a default my-default.ini file in the root and there is one server configuration:
So that does not tell me the path.
The best way is to connect to the database and run this query:
Here’s the result of that:
If you want to see all the parameters configured for the database execute this:
The storage_engine variable will tell you if you’re using InnoDb or MyISAM.
Search my.ini in disk, we will find this folder:
C:\ProgramData\MySQL\MySQL Server 8.0
It’s ProgramData , not Program file
Data is in sub-folder: \Data .
Each database owns a folder, each table is file, each index is 1+ files.
Here is a sample database sakila :
For Windows7 Use This Link: c:\users\all users\MySql\MySql Server x.x\Data\
Where x.x is the version number of the sql server installed in your machine.
That should be your
Just perform a Windows Search for *.myi files on your local partitions. Period.
As I suspectected, they were located inside a program files folder, instead of using a proper data-only folder like most other database managers do.
Why do a my.ini file search, open it with an editor, look-up the path string, make sure you don’t alter the config file (!), and then do a second search? Complicated without a shred of added benefit other than to practice touch typing.
If you’re using Win10 with Xampp server installed, then you can find the data folder in C:\xampp\mysql\data
Inside the data folder, each database has its own folder which in turn contains the .frm, .myi and .myd files which represent for a single table in the database.
If for instance, you created a database with the name: myschool and inside the database, you have three tables with the names:
- Nursery
- Primary
- Secondary
Then, you will have for the Nursery table: nursery.frm, nursery.myi and nursery.myd. Same will go for the Primary and Secondary tables. Thus, in the I mentioned here, you will a total of 9 files inside the database folder named myschool.
You can then copy the database folder and use it in your new mysql installation data folder.