Mysql перенос базы на другой диск windows

When you install “MySQL on Windows”,  the database Data Files are by default placed/located in “C:/ProgramData/MySQL/MySQL Server 5.1/Data/” folder as shown below:

image

As a best practice, a DBA would always like to have the DB data files to be placed on a separate drive/volume.  To change the folder location, you need to modify it in “MySQL Workbench” > Under Instance, Options File > General Tab > Directories > datadir and set the path to the folder on a another drive/volume (as shown below). Then click Apply.

image

Click Apply on the “Apply Changes to MYSQL Configuration File” (“C:\Program Files\MySQL\MySQL Server 5.1\my.ini”)

image

Then copy over the Data Files from initial location to the new location.  That is from “C:/ProgramData/MySQL/MySQL Server 5.1/Data/” to “D:/myDB” in above example.

Now, “MySQL Workbench” > Under Instance,  Startup / Shutdown MySQL Server” > click “Stop Server”

image

Rename the existing old Data Files location.  That is, “C:/ProgramData/MySQL/MySQL Server 5.1/Data/” to “C:/ProgramData/MySQL/MySQL Server 5.1/Data-OLD/”

<

p>Now Re-launch the “MySQL Workbench” then goto Under Instance,  Startup / Shutdown MySQL Server” > click “Start Server”.  Provide the password for the two prompts you receive.  Then now your MySQL should be running fine with Data Files being relocated or moved from it’s default  “C:/ProgramData/MySQL/MySQL Server 5.1/Data/” to “D:/myDB”.

When setting up MySQL on a Windows server, it is good practice to move the data folder to a secondary drive or partition. There’s a very important reason for this: you want to avoid having the database files & logs grow so large that they fill up the system drive. Follow the steps below to successfully move these files to a different location.

  1. Create the new location for the MySQL data to reside (ie. E:\MySQL\Data)
  2. Update the folder permissions on the new location to include the following (skipping this step will result in the MySQL server being unable to start after moving the data files): NETWORK SERVICE – Full Control
  3. Open Services and find the MySQL80 service – right-click it and Stop it
  4. Move all the contents from the default location: C:\ProgramData\MySQL\MySQL Server 8.0\Data to the new location
  5. Open the MySQL configuration file using NotePad++ (required for proper encoding): C:\ProgramData\MySQL\MySQL Server 8.0\my.ini
  6. Change the datadir variable to point to the new location: datadir = "E:/MySQL/Data"
  7. Save the changes and close the file
  8. Open Services and find the MySQL80 service – right-click it and Start it
  9. Open MySQL Workbench and connect to the server to ensure the databases are accessible.

From time to time it becomes necessary to optimize your system by changing where your data files and/or logs are located on the filesystem. While SQL Server is my primary platform, occasionally one has to use other systems; in this case mysql. Instructions are included for both database servers running on Windows OS.

Action Plan SQL Server

  1. Choose Method ( backup/restore OR detach/attach)
  2. Backup / Detach Database
  3. Restore Database / Move Data Files & Attach Database
  4. Test the Database

Action Plan MySQL

  1. Shutdown Service
  2. Change Configuration Options
  3. Restart Service
  4. Test the Service

This is how:

SQL SERVER

I opted to use the backup and restore method.

Backup the Database with the following command:

BACKUP DATABASE database_name TO DISK = N'T:\Backups\database_name.bak'
GO

Restore the database; the MOVE option will handle the copying of the files. You need to know the names logical names of the data files and log files. Use the sp_helpfile command to get this information prior to attempting the restore operation.

USE database_name
GO
sp_helpfile
GO

Restore the Database using the following syntax:
RESTORE DATABASE database_name
FROM DISK='T:\Backups\database_name.bak'
WITH MOVE 'database_name_data' TO 'D:\SQLData\database_name_data.mdf',
MOVE 'database_name_log' TO 'E:\SQLLogs\database_name_log.ldf',
REPLACE
GO

Test connectivity to the database.

MySQL

Shutdown the mysql server
Open the my.ini file found in the directory where you installed mysql usually “C:\Program Files\MySQL\MySQL Server 5.0\my.ini”
find the line
datadir="C:/Program Files/MySQL/MySQL Server 5.0/Data/"
Comment out the line, by putting a # sign in front of it.
Add a comment to document the change(date, time, reason).
Add a new line with the desired configuration
datadir="D:/MySQL Datafiles/data/"
Save the file.
Move/Copy the files to the new disk/location.
xcopy /D /E /C /V /Y /Z /H / "C:/Program Files/MySQL/MySQL Server 5.0/Data/" "D:/MySQL Datafiles/data/"

Start the mysql service.
Test the service, to ensure that all the databases are up, and accessible.
Delete files from the original location, if you copied files instead of moving them.

Conclusion

For me the great perk of using SQL Server is that this configuration is done at the individual database level. Therefore, there is no downtime on other hosted databases during a move of a database file. With mysql this configuration is managed for the entire instance, therefore all files for the instance must be contained in the same folder, so the move requires all your files be moved, and in doing so, downtime on all hosted databases.

Published by john.dacosta

I am a Database Consultant based in South Florida. I specialize in SQL Server Development and Administration. I have worked on projects including data archival, log shipping, SQL Server installation, performance tuning, database mirroring, disaster recovery and more recently data integration. Currently my role as a consultant has had me add focus to the particularly important subject of Documentation, Quality, Timeliness and Cross-Training within the realm of Technology Delivery.
View all posts by john.dacosta

Published

Возникает ситуация когда нужно перенести базы mysql в другое место. Например, на отдельный жесткий диск или просто в другое место. Это может быть необходимо, если не хватает места на диске или для увеличения быстродействия, например ssd винт или raid массив.

Способ 1

Если вы хотите выделить под БД полностью весь жесткий диск, то нужно просто примонтировать устройство в mysql директорию по умолчанию. Обычно это /var/lib/mysql Останавливаем сервер

/etc/init.d/mysqld stop

Копируем базы в какую-то временную директорию

mkdir /var/lib/mysql_temp
cp -r /var/lib/mysql/* /var/lib/mysql_temp/

удаляем базы со старой директории

rm /var/lib/mysql/* -Rf

Предполагается что у вас уже есть подготовленный жесткий диск. Если же нет, то его нужно предварительно разбить и создать файловую систему. Это можно сделать например при помощи cfdisk. И так примонтируем устройство:

mount /dev/sdb1 /var/lib/mysql

нужно не забыть прописать в файле /etc/fstab примонтированный раздел, для того что бы при следующей загрузке системы он автоматически монтировался. Более подробнее смотрите мануалы по fstab и mount. В fstab должна быть запись вида:

/dev/sdb1 /var/lib/mysql ext4 defaults 0 0

далее переносим назад наши базы

cp -r /var/lib/mysql_temp/* /var/lib/mysql/

и удаляем резервную копию (с этим лучше пока не спешить, удалить можно когда все успешно перенеслось)

rm /var/lib/mysql_temp/ -Rf

далее нужно правильно выставить права доступа к /var/lib/mysql. Владелец папки должен быть mysql c правом на запись

chown mysql:mysql /var/lib/mysql/ -R
chmod 755 /var/lib/mysql

а так же еще один важный момент, выставляем SELinux права доступа

chcon -R system_u:object_r:mysqld_db_t:s0 /var/lib/mysql/

проверить SELinux права можно командой ls -Z, должно быть что-то вроде этого:

ls -Z /var/lib/mysql/
drwxr-xr-x. mysql mysql system_u:object_r:mysqld_db_t:s0 mysql

теперь запускаем mysql демон

/etc/init.d/mysqld start

Способ 2

Если нужно использовать для хранилища не весь раздел, а только директорию на нем или переместить базы в другую директорию, то делаем следующее

останавливаем сервер

/etc/init.d/mysqld stop

копируем базы в новое место. Например, если мы хотим, что бы базы лежали в /media/sda3/mysql/

mkdir /media/sdb1/mysql/
cp -r /var/lib/mysql/* /media/sdb1/mysql/

ставим права доступа к /media/sdb1/mysql/

chown mysql:mysql /media/sdb1/mysql/ -R
chmod 755 /media/sdb1/mysql

а так же SELinux права доступа

chcon -R system_u:object_r:mysqld_db_t:s0 /media/sdb1/mysql/

правим конфиг my.cnf. Обычно он находится в /etc/my.cnf либо /etc/mysql/my.cnf

[mysqld]
datadir=/media/sdb1/mysql
socket=/media/sdb1/mysql/mysql.sock
log-bin=/media/sdb1/mysql/mysql-bin
[mysqld_safe]
datadir=/media/sdb1/mysql

теперь запускаем mysql демон

/etc/init.d/mysqld start

На этом всё. Если что-то не получается, смотрим лог в /var/log/mysql.log

🔍 Простой поиск по базе знаний

По умолчанию в Ubuntu  базы MySQL расположены в директории — «/var/lib/mysql». Иногда, по некоторым причинам возникает необходимость их переноса в другую директорию: например Вы захотели держать их на отдельном диске (локальном или сетевом) а диск автоматически монтируется в директорию, ну например, /mysqlbase. Перенос баз данных MySQL в другую директорию достаточно прост и состоит из нескольких шагов:

1. Останавливаем MySQL сервер

sudo service mysql stop

2. Переносим файлы баз данных в директорию «/mysqlbase»

sudo cp -R /var/lib/mysql/ /mysqlbase

3. Меняем владельца директории «/mysqlbase» и файлов находящихся в них на «mysql»

sudo chown -R mysql:mysql /mysqlbase

4. Редактируем файл «/etc/mysql/my.cnf»

sudo nano /etc/mysql/my.cnf

меняем значение пути к базам данных в строке «datadir = /var/lib/mysql» на «datadir = /mysqlbase»

5. Если в Ubuntu AppArmor не заглушен, то необходимо внести некоторые коррективы в его конфигурационный файл по работе с MySQL. Редактируем файл «/etc/apparmor.d/usr.sbin.mysqld»

sudo nano /etc/apparmor.d/usr.sbin.mysqld

Ищем в нем строки

/var/lib/mysql/ r,
/var/lib/mysql/** rwk,

и меняем на

/mysqlbase/ r,
/mysqlbase/** rwk,

6. Перезапускаем apparmor

sudo service apparmor restart

7. Запускаем сервер MySQL

sudo service mysql start

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Аниме гаджеты для рабочего стола windows 7
  • Флешка разделена на 2 диска как объединить windows 10
  • Msi afterburner windows 10 pro
  • Как установить linux mint второй системой с windows 10
  • Не работает разъем для наушников на ноутбуке windows 10