Показаны сообщения с ярлыком mysql. Показать все сообщения
Показаны сообщения с ярлыком mysql. Показать все сообщения

вторник, 27 марта 2012 г.

Mysql backup/restore

Просто положу здесь.

Use of mysqldump for taking backup of one table

In this section you will see the example of mysqldump function which takes the backup of only one table.

The mysqldump utility provides many options to take the backup of data as per user requirement. You can specify the name of table be backup in while executing the mysqldump utility.

Let's assume we have to take the backup of table1 from the mydatabase, then you can issue the following command on the console:

mysqldump -u -p mydatabase table1 > table1.sql

To restore the backup you can use the following command:

mysql -u -p mydatabase < table1.sql The mysqldump is very handy tool, it can be easily used to take the backup of only one table from the database. --- Dump ALL MySQL Databases mysqldump --user=XXXXXXXX --password=XXXXXXX -A > /PATH/TO/DUMPFILE.SQL

Dump Individual or Multiple MySQL Databases
mysqldump --user=XXXXXXXX --password=XXXXXXX --databases DB_NAME1 DB_NAME2 DB_NAME3 > /PATH/TO/DUMPFILE.SQL

Dump only certain tables from a MySQL Database
mysqldump --user=XXXXXXXX --password=XXXXXXXX --databases DB_NAME --tables TABLE_NAME > /PATH/TO/DUMPFILE.SQL

Use the following procedure to reload the contents of a database:
1. Unzip the backup file you wish to use.
2. Open it up and pull out only the information that you will need.
3. Save this text file.
4. Use the following command to feed back in the contents of a text file:
mysql --verbose --user=XXXXXXXX --password=XXXXXXXX DB_NAME < /PATH/TO/DUMPFILE.SQL

вторник, 9 марта 2010 г.

MYSQL user management

Нашёл в своих доках две полезные заметки по MYSQL.

Сброс пароля пользователя root в mysql.

Наша память, к сожалению, нас иногда подводит. И мы никак не можем вспомнить железно, как нам кажется, отпечатанный в памяти пароль. Вы можете сказать, что нужно иметь записную книжку а лучше две, и конечно будете правы. Но… Тем не менее иногда все-таки возникает необходимость восстановления забытого, либо утраченного пароля. Сегодня я опишу простой метод восстановления пароля суперпользователя root для базы данных mysql.

Для этого необходимо выполнить всего несколько шагов.
1. Останавливаем mysql.
service mysqld stop
2. Запускаем mysql следующей командой:

/usr/bin/mysqld_safe --skip-grant-tables --user=root &

3. Запускаем клиента mysql
mysql -u root
4. Выполняем sql запрос
UPDATE mysql.user SET Password=PASSWORD(’newpwd’) WHERE User=’root’;
где newpwd – новый пароль.
5. Применяем изменения
FLUSH PRIVILEGES;
6. Выходим из mysql клиента выполнив в нем команду exit
7. Перегружаем mysql сервер.
service mysqld restart

Ну и все на этом. Пароль суперпользователя root для базы данных mysql изменен. Добавлю, что конечно же этот метод описан в официальном руководстве по mysql, но может кому пригодится.

Оригинал: http://dedicatesupport.com/archives/30

И вторая:

Как создать пользователя mysql через cli

Небольшой пост о том, как создавать из командной строки mysql новую базу данных и нового пользователя mysql с полными правами на только что созданную базу.
mysql -uroot -p CREATE DATABASE ; GRANT ALL PRIVILEGES ON .* TO 'my_user'@'localhost' IDENTIFIED BY 'my_password' WITH GRANT OPTION;

Для того чтобы выставить новому пользователю полные права на все базы данных используем следующую команду:
GRANT ALL PRIVILEGES ON *.* TO 'my_user'@'localhost' IDENTIFIED BY 'my_password' WITH GRANT OPTION;

Доступ к базе для данного пользователя возможен только с localhost. Если вы хотите дать ему доступ к базе с любого хоста, используете % вместо localhost:
GRANT ALL PRIVILEGES ON .* TO 'my_user'@'%' IDENTIFIED BY 'my_password' WITH GRANT OPTION;

среда, 13 января 2010 г.

Cacti backup script

Много времени прошло с момента поднятия cacti на серваке. Написал скрипт для бэкапа, который рекурсивно копирует папку cacti со всеми скриптами и файлами графиков, сливает mysql базу и всё это заворачивает в tar и gzip. Можт кому будет интересно.

Собственно листинг:

#/usr/bin/bash

TMPDIR=/space/cacti_bkp
CACTIDIR=/usr/local/apache2/htdocs/cacti
BKPDIR=/space/
BKP=cacti_bkp

if test -d $TMPDIR
then rm -r $TMPDIR; mkdir $TMPDIR
else mkdir $TMPDIR
fi

echo "Copying files.."
(cp -R $CACTIDIR $TMPDIR)
wait

echo "Making SQL dump.."
/usr/local/mysql/bin/mysqldump -ucactiuser -pcactiuser --opt cacti > $TMPDIR/cacti_base.sql

echo "TARing files.."
tar cf $BKPDIR/$BKP.tar $TMPDIR

rm -r $TMPDIR
echo "GZIPing files.."

gzip -9 $BKPDIR/$BKP.tar
chown cacti:cacti $BKPDIR/$BKP.tar.gz
mv $BKPDIR/$BKP.tar.gz $BKPDIR/$BKP`date '+_%Y%m%d_%H%M%S'`.tar.gz

Результат работы скрипта:

-rw-r--r-- 1 cacti cacti 178235269 Jan 10 08:17 cacti_bkp_20100110_082232.tar.gz
-rw-r--r-- 1 cacti cacti 178720071 Jan 13 07:46 cacti_bkp_20100113_075147.tar.gz


В cron:
15 8 * * 0 sh /space/cacti_bkp.sh 1>/dev/null &
20 8 * * * find /space/*.gz -mtime 28 -exec rm {} \;

Первая строка собственно бэкап, вторая ищет старые бэкапы и трёт их.

среда, 25 ноября 2009 г.

Почистить транзакционные логи MySQL

12.6.1.1. PURGE BINARY LOGS Syntax

PURGE { BINARY | MASTER } LOGS
{ TO 'log_name' | BEFORE datetime_expr }

The binary log is a set of files that contain information about data modifications made by the MySQL server. The log consists of a set of binary log files, plus an index file.

The PURGE BINARY LOGS statement deletes all the binary log files listed in the log index file prior to the specified log file name or date. The log files also are removed from the list recorded in the index file, so that the given log file becomes the first.

This statement has no effect if the --log-bin option has not been enabled.

Examples:

PURGE BINARY LOGS TO 'mysql-bin.010';
PURGE BINARY LOGS BEFORE '2008-04-02 22:46:26';

The BEFORE variant's datetime_expr argument should evaluate to a DATETIME value (a value in 'YYYY-MM-DD hh:mm:ss' format). BINARY and MASTER are synonyms.

This statement is safe to run while slaves are replicating. You do not need to stop them. If you have an active slave that currently is reading one of the logs you are trying to delete, this statement does nothing and fails with an error. However, if a slave is dormant and you happen to purge one of the logs it has yet to read, the slave will be unable to replicate after it comes up.

To safely purge logs, follow this procedure:

1.

On each slave server, use SHOW SLAVE STATUS to check which log it is reading.
2.

Obtain a listing of the binary logs on the master server with SHOW BINARY LOGS.
3.

Determine the earliest log among all the slaves. This is the target log. If all the slaves are up to date, this is the last log on the list.
4.

Make a backup of all the logs you are about to delete. (This step is optional, but always advisable.)
5.

Purge all logs up to but not including the target log.

You can also set the expire_logs_days system variable to expire binary log files automatically after a given number of days (see Section 5.1.3, “Server System Variables”). If you are using replication, you should set the variable no lower than the maximum number of days your slaves might lag behind the master.

Prior to MySQL 5.0.60, PURGE BINARY LOGS TO and PURGE BINARY LOGS BEFORE did not behave in the same way (and neither one behaved correctly) when binary log files listed in the .index file had been removed from the system by some other means (such as using rm on Linux). Beginning with MySQL 5.0.60, both variants of the statement fail with an error in such cases. (Bug#18199, Bug#18453) You can handle such errors by editing the .index file (which is a simple text file) manually and insuring that it lists only the binary log files that are actually present, then running again the PURGE BINARY LOGS statement that failed.