Где лежат базы данных mysql windows

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...

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.

Sabito stands with Ukraine's user avatar

asked Oct 18, 2012 at 5:25

Brad's user avatar

4

You can check my.ini file to see where the data folder is located.

Usually there is a folder {mysqlDirectory}/data

MySQL data storage:

Commands.frm
Commands.myd
Commands.myi

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:ProgramDataMySQLMySQL Server 5.6data

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 /{database_name_folder}/{database_tables_and_files}.

For instance,

C:ProgramDataMySQLMySQL Server 5.6datamydatabasemytable.frm
C:ProgramDataMySQLMySQL Server 5.6datamydatabasemytable.ibd 

Thank @marty-mcgee for this content

answered Oct 18, 2012 at 5:27

Udan's user avatar

UdanUdan

5,3742 gold badges28 silver badges34 bronze badges

6

In Windows 7, the MySQL database is stored at

C:ProgramDataMySQLMySQL Server 5.6data

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.

Sabito stands with Ukraine's user avatar

answered Aug 10, 2013 at 21:06

Julio's user avatar

JulioJulio

5014 silver badges3 bronze badges

I have a default my-default.ini file in the root and there is one server configuration:

[mysqld]
sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES 

So that does not tell me the path.

The best way is to connect to the database and run this query:

SHOW VARIABLES WHERE Variable_Name LIKE "%dir" ;

Here’s the result of that:

basedir                     C:Program Files (x86)MySQLMySQL Server 5.6
character_sets_dir          C:Program Files (x86)MySQLMySQL Server 5.6sharecharsets

datadir                     C:ProgramDataMySQLMySQL Server 5.6Data
innodb_data_home_dir    
innodb_log_group_home_dir   .
lc_messages_dir             C:Program Files (x86)MySQLMySQL Server 5.6share

plugin_dir                  C:Program Files (x86)MySQLMySQL Server 5.6libplugin

slave_load_tmpdir           C:WindowsSERVIC~2NETWOR~1AppDataLocalTemp
tmpdir                      C:WindowsSERVIC~2NETWOR~1AppDataLocalTemp

If you want to see all the parameters configured for the database execute this:

SHOW VARIABLES;

The storage_engine variable will tell you if you’re using InnoDb or MyISAM.

answered Feb 12, 2015 at 4:05

Mukus's user avatar

MukusMukus

4,7742 gold badges41 silver badges56 bronze badges

1

MYSQL 8.0:

Search my.ini in disk, we will find this folder:

C:ProgramDataMySQLMySQL 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:
enter image description here

answered Sep 7, 2018 at 14:21

Dongdong's user avatar

DongdongDongdong

2,09017 silver badges26 bronze badges

1

For Windows7 Use This Link:
c:usersall usersMySqlMySql Server x.xData

Where x.x is the version number of the sql server installed in your machine.

Sabito stands with Ukraine's user avatar

answered Feb 2, 2014 at 7:40

user3256430's user avatar

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.

answered Oct 17, 2013 at 15:01

AleDB's user avatar

AleDBAleDB

911 bronze badge

1

If you’re using Win10 with Xampp server installed, then you can find the data folder in C:xamppmysqldata

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:

  1. Nursery
  2. Primary
  3. 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.

Sabito stands with Ukraine's user avatar

answered Apr 22, 2019 at 13:43

Saliu Muideen's user avatar

Community's user avatar

answered Oct 18, 2012 at 5:29

codingbiz's user avatar

codingbizcodingbiz

25.9k8 gold badges55 silver badges94 bronze badges

It’s usually in the folder specified below, but ProgramData is usually a hidden folder. To show it, go to control panel search for «folder» then under advanced settings tick show hidden files and click apply.
C:/ProgramData/MySQL/MySQL Server 5.5/Data/

answered Mar 1, 2016 at 8:25

B.K's user avatar

B.KB.K

82710 silver badges6 bronze badges

I just installed MySQL 5.7 on Windows7. The database files are located in the following directory which is a hidden one:
C:ProgramDataMySQLMySQL Server 5.7Data

The my.ini file is located in the same root: C:ProgramDataMySQLMySQL Server 5.7

Danny Nimmo's user avatar

answered Feb 19, 2017 at 11:12

Erik's user avatar

in MySQL are
«.myd» a database self and
«.tmd» a temporal file.
But sometimes I see also «.sql».

It depends on your settings and/or export method.

answered Sep 7, 2015 at 9:44

Alexander Khomenko's user avatar

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

For example,

C:Program FilesMySQLMySQL Server 5.1my.ini

2) Open the “my.ini” with our favor text editor.

#Path to installation directory. All paths are usually resolved relative to this.
basedir="C:/Program Files/MySQL/MySQL Server 5.1/"

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

Find the “datadir”, this is the where does MySQL stored the data in Windows.

answered Oct 18, 2012 at 5:30

Ami's user avatar

AmiAmi

4,2116 gold badges39 silver badges74 bronze badges

C:Program FilesMySQLMySQL Workbench 6.3 CEsys

paste URLin to window file,
and get Tables, Procedures, Functions from this directory

answered Feb 1, 2017 at 15:33

Muhammad Abbas's user avatar

Где хранятся данные MySQL на вашем компьютере

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

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

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

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

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

Бесплатный курс по PHP программированию

Освойте курс и узнайте, как создать веб-приложение на PHP с полного нуля

Получить курс сейчас!

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

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

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

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

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

Файл 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, где хранятся базы. Надеемся, нам удалось научить вас этому!

Бесплатный курс по PHP программированию

Освойте курс и узнайте, как создать веб-приложение на PHP с полного нуля

Получить курс сейчас!

Хотите изучить MySQL?

Посмотрите курс по базе данных MySQL!

Смотреть

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

Тематические термины: 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

Дмитрий Моск — частный мастер

Была ли полезна вам эта инструкция?

Да            Нет

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Whenever MySQL database installation is done, all the database related data and metadata are stored in one folder. This is the actual database schema with some values in it. Let us explore more about it. 

    The file extensions are as follows: 
     

    • .frm – This is the extension of file which contains the schema or definition of the table.
    • .myd – This is the extension of file which contains MyISAM table data.
    • .myi – This is the extension of file which contains MyISAM table indices.

    Inside the MySQL Server 5.5/data/mysql folder, some of the files are *.frm, *.MYD, and *.MYI
    where the asterisks are actual table names. If the MyISAM engine is used, the data folder will contain all the above files, otherwise in the case of InnoDB, the folder contains .frm files. 

    These database files are used for backup purpose for securing schema, data and indexes for some migration or upgrade of the database. The configuration files for MySQL for Windows and Linux are my.ini and my.conf respectively. 

    The Path for Windows: 

    C:Program FilesMySQLMySQL Server 5.5my.ini 

    In my.ini file, if we search the keyword basedir, we can get the path of the MySQL server installation. 

    In the similar way, if we search the keyword datadir, we can get the path of the Database root. Apart from this, there are many other files which are created or used by MySQL server to perform various activities. Some of them are as follows 

    • my.cnf
      Its a MySQL database configuration file. This is the main configuration file of MySQL server. 
      This is found in the root directory where the installation is done. In this file, the user can find the location of data folder. 
      The default location of the configuration file is ‘/etc/my.cnf‘ 
      Other file formats which are compatible with MySQL are .ibc, .tmd, .rul, .cnf, .ddl, .ibd, .mysql, .sql, .opt. 
      Depending on the table type, tables are stored in files with these extensions. 
       
    • db.opt
      Whenever database is created or changed using MySQL commands, the characteristics of database are stored in text file namely db.opt file . 
       
    • .ibd
      These are the files with extensions *.ibd which stores the data and index of MySQL InnoDB tables. This type of file is created or used by MySQL InnoDB software and associated with it . 
       
    • .sock
      All the MySQL database connections are managed by a special file called the socket file. This socket file namely mysqld.sock is created by MySQL service automatically which helps in communicating between different processes. 
       
    • Pid file
      The process id of MySQL server is written in such file. The default will be hostname of the MySQL server. 
       
    • .db
      These are the files with extensions ‘ .db ‘ which stores the data and indexes of BerkeleyDB storage engine. 
       
    • error log
      The error log file really plays an important role during troubleshooting of application. These are MySQL error log files which will give the exact reason or information for MySQL failure in the server. This effectively helps in the debug process for any error issue raised in MySQL server. By default it will log errors in hostname.err file. 
       
    • Slow Query Log
      Slow query log file have all the ‘ slow ‘ SQL queries. The performance of the application goes down because of the MySQL queries taking more time to complete than the expected result. So this helps in monitoring the slow queries which helps in improving the queries for higher performance. 
       
    • general query log
      General query log file gives all the general details like server start or end timings, up or down details, connect or disconnect details etc. It is enabled by log[=filename]. By default, MySQL will create hostname.log for the entries . 
       
    • binary log files
      The binary log files contains detail information related to any table creation or data modifications made to MySQL server. This also have information regarding the time taken by MySQL statement, state of the server, error codes, metadata for maintenance of log file. This is enabled by -log-bin[=basename] option. By default, its hostname of the server. 
       
    • .index
      To monitor which binary log files are used, a binary log index file is created which contains the names of all binary log files. It is enabled by –log-bin-index[=filename] else basename will be the binary log file with the extension .index. By default, relay log index file name is host_name-relay-bin.index . 
       
    • .TMD
      These are the intermediate database file created by MySQL server created during repair operations. This file contains information regarding database recoveries. These files are also be created by some other MySQL database operations. 
       
    • TRG and TRN Files
      TRG files are trigger parameter files and TRN files are trigger namespace files. In MySQL server, whenever triggers are defined, the definitions are stored in text files namely 
      tablename.TRG file. It contains triggers for multiple events like BEFORE or AFTER of INSERT, UPDATE or DELETE operations in MySQL. 
       
    • .ARZ, .ARM and .ARN files
      The table data and table metadata files have extensions of .ARZ and .ARM respectively. An .ARN file is the optimization file during optimization process. The files are related to Archive Storage Engine. 
       
    • .ARZ
      ARZ files are the metadata files for archive tables. The files with this extension stores data for table. The files are included in the backups created by mysqlbackup command of MySQL. 

    Improve Article

    Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Whenever MySQL database installation is done, all the database related data and metadata are stored in one folder. This is the actual database schema with some values in it. Let us explore more about it. 

    The file extensions are as follows: 
     

    • .frm – This is the extension of file which contains the schema or definition of the table.
    • .myd – This is the extension of file which contains MyISAM table data.
    • .myi – This is the extension of file which contains MyISAM table indices.

    Inside the MySQL Server 5.5/data/mysql folder, some of the files are *.frm, *.MYD, and *.MYI
    where the asterisks are actual table names. If the MyISAM engine is used, the data folder will contain all the above files, otherwise in the case of InnoDB, the folder contains .frm files. 

    These database files are used for backup purpose for securing schema, data and indexes for some migration or upgrade of the database. The configuration files for MySQL for Windows and Linux are my.ini and my.conf respectively. 

    The Path for Windows: 

    C:Program FilesMySQLMySQL Server 5.5my.ini 

    In my.ini file, if we search the keyword basedir, we can get the path of the MySQL server installation. 

    In the similar way, if we search the keyword datadir, we can get the path of the Database root. Apart from this, there are many other files which are created or used by MySQL server to perform various activities. Some of them are as follows 

    • my.cnf
      Its a MySQL database configuration file. This is the main configuration file of MySQL server. 
      This is found in the root directory where the installation is done. In this file, the user can find the location of data folder. 
      The default location of the configuration file is ‘/etc/my.cnf‘ 
      Other file formats which are compatible with MySQL are .ibc, .tmd, .rul, .cnf, .ddl, .ibd, .mysql, .sql, .opt. 
      Depending on the table type, tables are stored in files with these extensions. 
       
    • db.opt
      Whenever database is created or changed using MySQL commands, the characteristics of database are stored in text file namely db.opt file . 
       
    • .ibd
      These are the files with extensions *.ibd which stores the data and index of MySQL InnoDB tables. This type of file is created or used by MySQL InnoDB software and associated with it . 
       
    • .sock
      All the MySQL database connections are managed by a special file called the socket file. This socket file namely mysqld.sock is created by MySQL service automatically which helps in communicating between different processes. 
       
    • Pid file
      The process id of MySQL server is written in such file. The default will be hostname of the MySQL server. 
       
    • .db
      These are the files with extensions ‘ .db ‘ which stores the data and indexes of BerkeleyDB storage engine. 
       
    • error log
      The error log file really plays an important role during troubleshooting of application. These are MySQL error log files which will give the exact reason or information for MySQL failure in the server. This effectively helps in the debug process for any error issue raised in MySQL server. By default it will log errors in hostname.err file. 
       
    • Slow Query Log
      Slow query log file have all the ‘ slow ‘ SQL queries. The performance of the application goes down because of the MySQL queries taking more time to complete than the expected result. So this helps in monitoring the slow queries which helps in improving the queries for higher performance. 
       
    • general query log
      General query log file gives all the general details like server start or end timings, up or down details, connect or disconnect details etc. It is enabled by log[=filename]. By default, MySQL will create hostname.log for the entries . 
       
    • binary log files
      The binary log files contains detail information related to any table creation or data modifications made to MySQL server. This also have information regarding the time taken by MySQL statement, state of the server, error codes, metadata for maintenance of log file. This is enabled by -log-bin[=basename] option. By default, its hostname of the server. 
       
    • .index
      To monitor which binary log files are used, a binary log index file is created which contains the names of all binary log files. It is enabled by –log-bin-index[=filename] else basename will be the binary log file with the extension .index. By default, relay log index file name is host_name-relay-bin.index . 
       
    • .TMD
      These are the intermediate database file created by MySQL server created during repair operations. This file contains information regarding database recoveries. These files are also be created by some other MySQL database operations. 
       
    • TRG and TRN Files
      TRG files are trigger parameter files and TRN files are trigger namespace files. In MySQL server, whenever triggers are defined, the definitions are stored in text files namely 
      tablename.TRG file. It contains triggers for multiple events like BEFORE or AFTER of INSERT, UPDATE or DELETE operations in MySQL. 
       
    • .ARZ, .ARM and .ARN files
      The table data and table metadata files have extensions of .ARZ and .ARM respectively. An .ARN file is the optimization file during optimization process. The files are related to Archive Storage Engine. 
       
    • .ARZ
      ARZ files are the metadata files for archive tables. The files with this extension stores data for table. The files are included in the backups created by mysqlbackup command of MySQL. 

    Быстрый ответ

    Сперва быстро отвечу, а потому изложу подрбно почему именно так. Путь к базам данных содержит переменная сервера @@datadir и директива конфигурационного файла datadir.

    Глобальная переменная datadir

    Делаем SQL-запрос запрашивая содержимое глобальной переменной datadir в которой и находится путь к файлам баз данных и таблиц:

    select @@datadir;
    

    Директива datadir

    Физический путь к файлам БД/таблиц (директория с физическими файлами баз данных) задан в директиве datadir главного конфигурационного файла СУБД MySQL «my.cnf». Там будет что-то вроде такого:

    [mysqld]
    ...
    datadir=/var/lib/mysql
    ...
    

    Это будет полезно в том случае если сервер БД выключен и выполнить SQL-запрос, описанный выше, нельзя.

    Пояснения

    Естественно файлы баз данных не будут лежать в папке самого сервера MySQL т.к. это противоречит общей политики распределения программных и пользовательских файлов, в том числе и политике разделения данных Microsoft.

    Файлы баз данных (точнее таблиц) расположены в следующих директориях:
    Для Windows XP:
    c:Documents and SettingsAll UsersApplication DataMySQLMySQL Server x.xdata

    Для Windows 7:
    c:ProgramDataMySQLMySQL Server x.xdata

    В этой папке data будут другие директории, это базы данных, их названия будут об этом говорить, т.е. названия папок такие же как и названия баз данных. В них находятся собственно файлы таблиц, имена которых совпадают с именами этих таблиц в MySQL.

    А вообще узнать где лежат файлы таблиц и баз данных можно из окна свойств службы MySQL server. Заходим в службы и ищем mysql, открываем свойства службы и находим заголовок «Исполняемый файл», там будет, что-то вроде этого:

    «C:Program FilesMySQLMySQL Server 5.6binmysqld» —defaults-file=»C:ProgramDataMySQLMySQL Server 5.6my.ini» MySQL56

    В параметре ключа «—defaults-file» прописан путь к файлу конфигурации сервера по умолчанию — my.ini. В этой же папке и будет директория data с папками баз данных в которых лежат файлы таблиц.

    0 / 0 / 0

    Регистрация: 26.04.2011

    Сообщений: 25

    1

    28.03.2012, 13:01. Показов 47339. Ответов 20


    Добрый день. Вот поставила MySQL. Через консоль создала базу, создала таблицу. Заполнила ее. А как сохранить то? смотрела в файл My.ini. Так указан путь сохранения базы в папке Data. Но вот нет у меня там базы никакой…. Где она сохраняется то в итоге??? Дорогие форумчане, помогите советом, пожалуйста…

    __________________
    Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



    0



    770 / 760 / 59

    Регистрация: 06.07.2009

    Сообщений: 3,021

    28.03.2012, 13:09

    2

    Неумеха, А вам для чего это вообще нужно?
    А вообще папка с базой должна появляться в data, если вы базу создали реально.



    0



    0 / 0 / 0

    Регистрация: 14.02.2013

    Сообщений: 3

    14.02.2013, 18:58

    3

    c:ProgramDataMySQL
    Полный путь у меня c:ProgramDataMySQLMySQL Server 5.1data
    после переустановки windows всё взял из C:Windows.oldProgramDataMySQLMySQL Server 5.1data



    0



    79 / 55 / 0

    Регистрация: 29.01.2013

    Сообщений: 254

    Записей в блоге: 1

    14.02.2013, 21:59

    4

    Это «по умолчанию».
    Но если во время инсталляции не прозевать один момент, то можно установить базу в любой другой каталог (его надо заранее завести) — там появится один файл, не помню, как называется. Таким образом, если Вы помещаете базу на тот же компьютер, на котором работаете (localhost), то можете выполнить рекомендацию «не хранить все яйца в одной корзине» и поместить этот файл не на системный, а на другой диск, а бэкапы делать на системный (а я еще копировал и на выносной). Если есть второй диск и особенно если процессор двух- и более ядерный, то получится еще и ощутимое приращение скорости работы программы с этой базой.



    0



    2649 / 2270 / 279

    Регистрация: 24.12.2010

    Сообщений: 13,725

    01.05.2013, 19:11

    5

    Путь к директории с базами данных, с которыми Мускул-сервер способен будет работать после старта, указан в файле my.ini, находящемся по умолчанию в корневой директории инсталляции Мускул-сервера.

    Например,

    #Path to the database root
    datadir=»C:/ProgramData/MySQL/MySQL Server 5.5/Data/»



    0



    Vovan-VE

    13207 / 6595 / 1041

    Регистрация: 10.01.2008

    Сообщений: 15,069

    02.05.2013, 08:11

    6

    Лучший ответ Сообщение было отмечено как решение

    Решение

    MySQL
    1
    2
    3
    4
    5
    6
    
    mysql> SELECT @@datadir;
    +-----------------+
    | @@datadir       |
    +-----------------+
    | /var/lib/mysql/ |
    +-----------------+



    5



    28 / 24 / 2

    Регистрация: 11.12.2012

    Сообщений: 448

    02.09.2013, 15:15

    7

    Аналогичная проблема. Смотрю курсы от Специалиста, но там создается папка в data по запросу CREATE DATABASE web; У меня же ничего в этой папке не видно. В my.ini прописано #Path to the database root
    datadir=»C:/ProgramData/MySQL/MySQL Server 5.5/Data/». Запросы по папке выполняются и повторно ее не могу создать, так как пишется, что она уже существует. А где она?



    0



    79 / 55 / 0

    Регистрация: 29.01.2013

    Сообщений: 254

    Записей в блоге: 1

    03.09.2013, 04:36

    8

    Вот именно там и создаются все базы. Создаются папки с именами, соответствующими именам баз (в вашем случае должна быть папка с именем Вашей базы, а также папки системных баз), и еще несколько файлов. Если их там нет, ну, значит, где-то накосячили при установке мускула. Может быть много разных причин: изменили место установки вместо предлагаемого стандартного, системный диск у вас не С: и т.д. Поищите базу (папку) mysql где-нибудь в других местах. Если всё работает, до должна же быть где-то база , чудес, как правило, не бывает.
    Кстати, а базу-то Вы действительно создали? Вы же пишете, что не смогли сохранить. На всякий случай напишите в конце вашего рукописного скрипта «аминь», то есть commit.



    0



    770 / 760 / 59

    Регистрация: 06.07.2009

    Сообщений: 3,021

    03.09.2013, 05:12

    9

    Euroman, Поищите в служебных папках C:Usersимя пользователяAppDataLocalVirtualStoreProgram Filesназвание программы



    0



    28 / 24 / 2

    Регистрация: 11.12.2012

    Сообщений: 448

    03.09.2013, 14:02

    10

    Цитата
    Сообщение от Гаврилов-50
    Посмотреть сообщение

    Вы же пишете, что не смогли сохранить.

    Где я такое написал?

    Добавлено через 9 минут

    Цитата
    Сообщение от solar_wind
    Посмотреть сообщение

    Euroman, Поищите в служебных папках C:Usersимя пользователяAppDataLocalVirtualStoreProgram Filesназвание программы

    Порылся в той области, но что-то не нашел. Папки Program Files в Virtual Store у меня нету. Но база точно где-то сохранена, раз пишется, что она уже существует, и я могу просматривать ее в консоли. А можно что-то прописать в консоли, чтобы узнать, где находится папка?



    0



    79 / 55 / 0

    Регистрация: 29.01.2013

    Сообщений: 254

    Записей в блоге: 1

    03.09.2013, 20:00

    11

    Был один раз у меня случай, о котором я долго сомневался, стоит ли написать. Дело в том, что я не могу вспомнить, при каких обстоятельствах и в каком каталоге у меня появился в результате инсталляции MySQL единственный файл data1 (или Data1). Видимо, он содержал все базы, обычно создаваемые по умолчанию. Я добавил еще две или три базы, но файл остался один, только вырос в размере. Вот такая получилась странная инсталляция. Может быть, этот пример натолкнет вас на какую-нибудь мысль.



    0



    sqlnub

    Заблокирован

    07.09.2013, 06:08

    12

    Зачем вам эти файлы? Все равно с ними ничего нельзя сделать просто так. И где они лежат приходится узнавать только от нужды что-то там грохнуть что не грохнулось из командной строки.

    Добавлено через 3 минуты

    Цитата
    Сообщение от Неумеха
    Посмотреть сообщение

    А как сохранить то?

    Сохранение базы, таблицы, процедуры и прочих сущностей делается через текст который дает дамп базы, таблицы, процедуры и прочих сущностей, который можно сохранить в текстовый файл.

    Добавлено через 3 минуты
    Прочитайте в своем туториале как делать дампы и как из сохраненных в текстовых файлов дампов делать сущности.



    0



    79 / 55 / 0

    Регистрация: 29.01.2013

    Сообщений: 254

    Записей в блоге: 1

    08.09.2013, 03:53

    13

    Как это «зачем вам эти файлы?». Странный вопрос для форума такого уровня.
    Это пользователю — «зачем», да и то не всякому. А программист должен знать, где у него хранится информация. Зачем? Хотя бы затем, чтобы понимать, куда он должен класть резервные копии — как правило, не в ту же корзину, где находится база.



    0



    sqlnub

    Заблокирован

    08.09.2013, 23:47

    14

    Действительно, для форума такого только еще бреда не доставало.

    В майскуле никто в здравом уме файлами таблиц не оперирует. Все делается через дампы и запросы. В том числе все бэкапы автоматические это дампы.

    Дело даже не в том что ваши таблицы повязаны с не вашими типа information_schema, а в том что как правило до файлов вообще не добраться. Они лежат в папке выше папки сайта куда типичных клиентов типичный хостер никогда не допустит. Только не дедике вы можете их увидеть как таковые, ну, чисто посмотреть — вот они мои яй.. файлы, лежат. Кроме того бд в майскуле это вовсе не один файл как вы наверно подумали по аналогии с абсцессом.

    И еще у них имена могут быть такими: @t0@g0@x0@y0@w0@u0@p0@q0@o0.MYD — вам уже понятно как называется эта таблица?



    0



    231 / 12 / 3

    Регистрация: 28.12.2012

    Сообщений: 192

    14.09.2013, 13:55

    15

    во всей файловой системе ищите файлы с названиями таблиц вашей базы и самой базы, найдёте полюбому. А вообще Vovan-VE уже всё сказал правильно.



    0



    sqlnub

    Заблокирован

    16.09.2013, 10:33

    16

    Цитата
    Сообщение от sqlnub
    Посмотреть сообщение

    @t0@g0@x0@y0@w0@u0@p0@q0@o0

    И такое по любому?



    0



    Модератор

    4188 / 3028 / 576

    Регистрация: 21.01.2011

    Сообщений: 13,104

    16.09.2013, 11:05

    17

    Цитата
    Сообщение от Гаврилов-50
    Посмотреть сообщение

    А программист должен знать, где у него хранится информация. Зачем? Хотя бы затем, чтобы понимать, куда он должен класть резервные копии — как правило, не в ту же корзину, где находится база.

    Как правило, это (в том числе бэкапы) — забота DBA, а не программиста. И при нормальной организации труда программистов, как и пользователей, на сервер просто не пускают.



    0



    0 / 0 / 0

    Регистрация: 20.09.2013

    Сообщений: 21

    02.10.2013, 17:02

    18

    Добавлено через 22 минуты

    Цитата
    Сообщение от Kamila_
    Посмотреть сообщение

    Кто-нибудь подскажите, как создать бд и сохранить ее в конкретной папке (через командную строку)? Я тоже свою не нашла. Мне по заданию надо бэкап БД предоставить. Как его сделать?

    Вроде разобралась! Кому вдруг интересно будет, помогло это:

    C:Program FilesMySQLMySQL Server 5.5bin>mysqldump -u root -p -f mybd > C:mydump.sql
    Enter password: ****



    0



    1 / 1 / 0

    Регистрация: 04.10.2017

    Сообщений: 2

    04.02.2019, 11:32

    19

    Доброго времени суток! Тоже столкнулся с такой проблемой, что установленной директиве программы не было папки DATA. Проковырял все возможные папки и запустил поиск, результатом оказалось нахождением в следующем пути:
    C:ProgramDataMySQLMySQL Server 6.0data

    Может кому помог этим сообщением



    1



    0 / 0 / 0

    Регистрация: 11.01.2022

    Сообщений: 4

    09.11.2022, 00:05

    20

    ctapbludpyr, спасибо большое, твердо и четко все написал



    0



    Понравилась статья? Поделить с друзьями:
  • Где лежат ssh в windows 10
  • Где лежит sam файл в windows 10
  • Где лежат icc профили в windows 10
  • Где лежит paint exe windows 11
  • Где лежат dll файлы в windows 10