- Linux и Windows: помощь админам и пользователям
- Администрируем и настраиваем Windows, Linux.
- 15 практических примеров использования команд Mysqladmin для администрирования MySQL сервера
- 2. Как проверить работает ли MySQL сервер?
- 3. Как посмотреть какая версия MySQL используетсяI am running?
- 4. Как посмотреть статус MySQL сервера?
- 5. Как просмотреть статус переменных MySQL и их текущее значение?
- 6. Как отобразить все системные переменные MySQL сервера и их значения?
- 7. Как отобразить все запущенные процессы/запросы в базе mysql?
- 8. Как создать базу MySQL?
- 9. Как удалить существующую базу MySQL?
- 10. Как перегрузить все привилегии и права на таблицы?
- 11. Как образом выполнить безопасную остановку MySQL сервера?
- 12. Список всех mysqladmin flush комманд.
- 13. Как убить подвешенный клиентский процесс в MySQL ?
- 14. Как запустить или остановить репликацию MySQL на slave-сервер?
- 15. Как скомбинировать несколько команд mysqladmin вместе?
- Устраняем типичные ошибки в MySQL
- Не удаётся подключиться к локальному серверу
- Не удаётся подключиться к серверу MySQL
- Ошибки запрета доступа в MySQL
- Потеря соединения с сервером MySQL
- Слишком много подключений
- Недостаточно памяти
- MySQL продолжает «падать»
- Заключение
- Mysql server status windows
- Mysql server status windows
- Mysql server status windows
Linux и Windows: помощь админам и пользователям
Администрируем и настраиваем Windows, Linux.
15 практических примеров использования команд Mysqladmin для администрирования MySQL сервера
В 15 примерах использования команд mysqladmin ниже, используется пароль root Mysql tmppassword. Поменяйте его на ваш пароль
1. Как изменить пароль root на Mysql?
2. Как проверить работает ли MySQL сервер?
3. Как посмотреть какая версия MySQL используетсяI am running?
[cut]Эта команда так же отображает текущий статус сервера.
4. Как посмотреть статус MySQL сервера?
Команда status отображает следующую информациюcommand displays the following information:
- Uptime: Время безотказной работы в секундах
- Threads: Общее количество клиентов, подключенных к серверу.
- Questions: Общее количество запросов к серверу с момента запуска.
- Slow queries: Общее количество запросов, чьё время выполнения было больше чем значение переменной long_query_time.
- Opens: Total number of tables opened by the server.
- Flush tables: How many times the tables were flushed.
- Open tables: Total number of open tables in the database.
5. Как просмотреть статус переменных MySQL и их текущее значение?
6. Как отобразить все системные переменные MySQL сервера и их значения?
7. Как отобразить все запущенные процессы/запросы в базе mysql?
Вы можете использовать эту команду для эффективного дебага любых проблем с производительностью и определять процесс, который вызывает проблемы, запустив команду на автообновление каждую секунду.
8. Как создать базу MySQL?
Замечание: Для отображения все таблиц в базе данных, общего количества колонок, строк, индексов и прочее. используйте команду mysqlshow.
9. Как удалить существующую базу MySQL?
10. Как перегрузить все привилегии и права на таблицы?
Команда Refresh сбросит все таблица и закроет/откроет лог-файлы.
11. Как образом выполнить безопасную остановку MySQL сервера?
Вы можете использовать команду “/etc/rc.d/init.d/mysqld stop” для остановки сервера. Для запуска выполните “/etc/rc.d/init.d/mysql start”
12. Список всех mysqladmin flush комманд.
- flush-hosts: Сбросить всю информацию в кэше хостов.
- flush-privileges: Перезагрузить права.
- flush-status: Очистить статус переменных.
- flush-threads: Flush the thread cache.
13. Как убить подвешенный клиентский процесс в MySQL ?
Сперва определите подвешенный процесс используя команду processlist.
Затем используйте команду kill и нужный process_id. Для завершения нескольких процессов разделите process id запятыми.
14. Как запустить или остановить репликацию MySQL на slave-сервер?
15. Как скомбинировать несколько команд mysqladmin вместе?
В примере ниже скомбинированы команды process-list, status и version для полного вывода статуса сервера.
Вы можете также использовать краткую форму записи:
Используйте опцию -h для подключения к удаленному MySQL серверу и выполнения команды.
Постовой
Покупайте ламинат только в интернет-магазине «Паркет-Всем». Самые выгодные ценовые предложения, огромный ассортимент и удобная доставка.
Купить оригинальные японские запчасти в интернет магазине «Tan Sin» это самое лучшее, что вы можете сделать для своего автомобиля.
Устраняем типичные ошибки в MySQL
MySQL — система управления базами данных (СУБД) с открытым исходным кодом от компании Oracle. Она была разработана и оптимизирована специально для работы веб-приложений. MySQL является неотъемлемой частью таких веб-сервисов, как Facebook, Twitter, Wikipedia, YouTube и многих других.
Эта статья расскажет, как определять, с чем связаны частые ошибки на сервере MySQL, и устранять их.
Не удаётся подключиться к локальному серверу
Одной из распространённых ошибок подключения клиента к серверу является «ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock’ (2)».
Эта ошибка означает, что на хосте не запущен сервер MySQL ( mysqld ) или вы указали неправильное имя файла сокета Unix или порт TCP/IP при попытке подключения.
Убедитесь, что сервер работает. Проверьте процесс с именем mysqld на хосте сервера, используя команды ps или grep, как показано ниже.
Если эти команды не показывают выходных данных, то сервер БД не работает. Поэтому клиент не может подключиться к нему. Чтобы запустить сервер, выполните команду systemctl.
Чтобы проверить состояние службы MySQL, используйте следующую команду:
Если в результате выполнения команды произошла ошибка службы MySQL, вы можете попробовать перезапустить службу и ещё раз проверить её состояние.
Если сервер работает (как показано) и вы по-прежнему видите эту ошибку, вам следует проверить, не заблокирован ли порт TCP/IP брандмауэром или любой другой службой блокировки портов.
СберЗдоровье , Удалённо , По итогам собеседования
Для поиска порта, который прослушивается сервером, используйте команду netstat .
Не удаётся подключиться к серверу MySQL
Ещё одна похожая и часто встречающаяся ошибка подключения — «(2003) Can’t connect to MySQL server on ‘server’ (10061)». Это означает, что в сетевом соединении было отказано.
Следует проверить, работает ли в системе сервер MySQL (смотрите выше) и на тот ли порт вы подключаетесь (как найти порт, можно посмотреть выше).
Похожие частые ошибки, с которыми вы можете столкнуться при попытке подключиться к серверу MySQL:
Ошибки запрета доступа в MySQL
В MySQL учётная запись (УЗ) определяется именем пользователя и клиентским хостом, с которого пользователь может подключиться. УЗ может также иметь данные для аутентификации (например, пароль).
Причин для запрета доступа может быть много. Одна из них связана с учётными записями MySQL, которые сервер разрешает использовать клиентским программам при подключении. Это означает, что имя пользователя, указанное в соединении, может не иметь прав доступа к базе данных.
В MySQL есть возможность создавать учётные записи, позволяющие пользователям клиентских программ подключаться к серверу и получать доступ к данным. Поэтому при ошибке доступа проверьте разрешение УЗ на подключение к серверу через клиентскую программу.
Увидеть разрешённые привилегии учётной записи можно, выполнив в консоли команду SHOW GRANTS
Входим в консоль (пример для Unix, для Windows консоль можно найти в стартовом меню):
В консоли вводим команду:
Дать привилегии конкретному пользователю в БД по IP-адресу можно, используя следующие команды:
Ошибки запрещённого доступа могут также возникнуть из-за проблем с подключением к MySQL (см. выше).
Потеря соединения с сервером MySQL
С этой ошибкой можно столкнуться по одной из следующих причин:
- плохое сетевое соединение;
- истекло время ожидания соединения;
- размер BLOB больше, чем max_allowed_packet .
В первом случае убедитесь, что у вас стабильное сетевое подключение (особенно, если подключаетесь удалённо).
Если проблема с тайм-аутом соединения (особенно при первоначальном соединении MySQL с сервером), увеличьте значение параметра connect_timeout .
В случае с размером BLOB нужно установить более высокое значение для max_allowed_packet в файле конфигурации /etc/my.cnf в разделах [mysqld] или [client] как показано ниже.
Если файл конфигурации недоступен, это значение можно установить с помощью следующей команды.
Слишком много подключений
Эта ошибка означает, что все доступные соединения используются клиентскими программами. Количество соединений (по умолчанию 151) контролируется системной переменной max_connections . Устранить проблему можно, увеличив значение переменной в файле конфигурации /etc/my.cnf .
Недостаточно памяти
Если такая ошибка возникла, это может означать, что в MySQL недостаточно памяти для хранения всего результата запроса.
Сначала нужно убедиться, что запрос правильный. Если это так, то нужно выполнить одно из следующих действий:
- если клиент MySQL используется напрямую, запустите его с ключом —quick switch , чтобы отключить кешированные результаты;
- если вы используете драйвер MyODBC, пользовательский интерфейс (UI) имеет расширенную вкладку с опциями. Отметьте галочкой «Do not cache result» (не кешировать результат).
Также может помочь MySQL Tuner. Это полезный скрипт, который подключается к работающему серверу MySQL и даёт рекомендации по настройке для более высокой производительности.
MySQL продолжает «падать»
Если такая проблема возникает, необходимо выяснить, заключается она в сервере или в клиенте. Обратите внимание, что многие сбои сервера вызваны повреждёнными файлами данных или индексными файлами.
Вы можете проверить состояние сервера, чтобы определить, как долго он работал.
Чтобы узнать время безотказной работы сервера, запустите команду mysqladmin .
Кроме того, можно остановить сервер, сделать отладку MySQL и снова запустить службу. Для отображения статистики процессов MySQL во время выполнения других процессов откройте окно командной строки и введите следующее:
Заключение
Самое важное при диагностике — понять, что именно вызвало ошибку. Следующие шаги помогут вам в этом:
- Первый и самый важный шаг — просмотреть журналы MySQL, которые хранятся в каталоге /var/log/mysql/ . Вы можете использовать утилиты командной строки вроде tail для чтения файлов журнала.
- Если служба MySQL не запускается, проверьте её состояние с помощью systemctl . Или используйте команду journalctl (с флагом -xe ) в systemd.
- Вы также можете проверить файл системного журнала (например, /var/log/messages ) на предмет обнаружения ошибок.
- Попробуйте использовать такие инструменты, как Mytop, glances, top, ps или htop, чтобы проверить, какая программа использует весь ресурс процессора или блокирует машину. Они также помогут определить нехватку памяти, дискового пространства, файловых дескрипторов или какого-либо другого важного ресурса.
- Если проблема в каком-либо процессе, можно попытаться его принудительно остановить, а затем запустить (при необходимости).
- Если вы уверены, что проблемы именно на стороне сервера, можете выполнить команды: mysqladmin -u root ping или mysqladmin -u root processlist , чтобы получить от него ответ.
- Если при подключении проблема не связана с сервером, проверьте, нормально ли работает клиент. Попробуйте получить какие-либо его выходные данные для устранения неполадок.
Mysql server status windows
The MySQL server can be started manually from the command line. This can be done on any version of Windows.
To start the mysqld server from the command line, you should start a console window (or “ DOS window ” ) and enter this command:
The path to mysqld may vary depending on the install location of MySQL on your system.
You can stop the MySQL server by executing this command:
If the MySQL root user account has a password, you need to invoke mysqladmin with the -p option and supply the password when prompted.
This command invokes the MySQL administrative utility mysqladmin to connect to the server and tell it to shut down. The command connects as the MySQL root user, which is the default administrative account in the MySQL grant system.
Users in the MySQL grant system are wholly independent from any operating system users under Microsoft Windows.
If mysqld doesn’t start, check the error log to see whether the server wrote any messages there to indicate the cause of the problem. By default, the error log is located in the C:\Program Files\MySQL\MySQL Server 8.0\data directory. It is the file with a suffix of .err , or may be specified by passing in the —log-error option. Alternatively, you can try to start the server with the —console option; in this case, the server may display some useful information on the screen to help solve the problem.
Mysql server status windows
SHOW STATUS provides server status information (see Section 5.1.10, “Server Status Variables”). This statement does not require any privilege. It requires only the ability to connect to the server.
Status variable information is also available from these sources:
For SHOW STATUS , a LIKE clause, if present, indicates which variable names to match. A WHERE clause can be given to select rows using more general conditions, as discussed in Section 26.55, “Extensions to SHOW Statements”.
SHOW STATUS accepts an optional GLOBAL or SESSION variable scope modifier:
With a GLOBAL modifier, the statement displays the global status values. A global status variable may represent status for some aspect of the server itself (for example, Aborted_connects ), or the aggregated status over all connections to MySQL (for example, Bytes_received and Bytes_sent ). If a variable has no global value, the session value is displayed.
With a SESSION modifier, the statement displays the status variable values for the current connection. If a variable has no session value, the global value is displayed. LOCAL is a synonym for SESSION .
If no modifier is present, the default is SESSION .
The scope for each status variable is listed at Section 5.1.10, “Server Status Variables”.
Each invocation of the SHOW STATUS statement uses an internal temporary table and increments the global Created_tmp_tables value.
Partial output is shown here. The list of names and values may differ for your server. The meaning of each variable is given in Section 5.1.10, “Server Status Variables”.
With a LIKE clause, the statement displays only rows for those variables with names that match the pattern:
Mysql server status windows
On Windows, the recommended way to run MySQL is to install it as a Windows service, so that MySQL starts and stops automatically when Windows starts and stops. A MySQL server installed as a service can also be controlled from the command line using NET commands, or with the graphical Services utility. Generally, to install MySQL as a Windows service you should be logged in using an account that has administrator rights.
The Services utility (the Windows Service Control Manager ) can be found in the Windows Control Panel. To avoid conflicts, it is advisable to close the Services utility while performing server installation or removal operations from the command line.
Installing the service
Before installing MySQL as a Windows service, you should first stop the current server if it is running by using the following command:
If the MySQL root user account has a password, you need to invoke mysqladmin with the -p option and supply the password when prompted.
This command invokes the MySQL administrative utility mysqladmin to connect to the server and tell it to shut down. The command connects as the MySQL root user, which is the default administrative account in the MySQL grant system.
Users in the MySQL grant system are wholly independent from any operating system users under Windows.
Install the server as a service using this command:
The service-installation command does not start the server. Instructions for that are given later in this section.
To make it easier to invoke MySQL programs, you can add the path name of the MySQL bin directory to your Windows system PATH environment variable:
On the Windows desktop, right-click the My Computer icon, and select Properties .
Next select the Advanced tab from the System Properties menu that appears, and click the Environment Variables button.
Under System Variables , select Path , and then click the Edit button. The Edit System Variable dialogue should appear.
Place your cursor at the end of the text appearing in the space marked Variable Value . (Use the End key to ensure that your cursor is positioned at the very end of the text in this space.) Then enter the complete path name of your MySQL bin directory (for example, C:\Program Files\MySQL\MySQL Server 8.0\bin ), and there should be a semicolon separating this path from any values present in this field. Dismiss this dialogue, and each dialogue in turn, by clicking OK until all of the dialogues that were opened have been dismissed. You should now be able to invoke any MySQL executable program by typing its name at the DOS prompt from any directory on the system, without having to supply the path. This includes the servers, the mysql client, and all MySQL command-line utilities such as mysqladmin and mysqldump .
You should not add the MySQL bin directory to your Windows PATH if you are running multiple MySQL servers on the same machine.
You must exercise great care when editing your system PATH by hand; accidental deletion or modification of any portion of the existing PATH value can leave you with a malfunctioning or even unusable system.
The following additional arguments can be used when installing the service:
You can specify a service name immediately following the —install option. The default service name is MySQL .
If a service name is given, it can be followed by a single option. By convention, this should be —defaults-file= file_name to specify the name of an option file from which the server should read options when it starts.
The use of a single option other than —defaults-file is possible but discouraged. —defaults-file is more flexible because it enables you to specify multiple startup options for the server by placing them in the named option file.
You can also specify a —local-service option following the service name. This causes the server to run using the LocalService Windows account that has limited system privileges. If both —defaults-file and —local-service are given following the service name, they can be in any order.
For a MySQL server that is installed as a Windows service, the following rules determine the service name and option files that the server uses:
If the service-installation command specifies no service name or the default service name ( MySQL ) following the —install option, the server uses the service name of MySQL and reads options from the [mysqld] group in the standard option files.
If the service-installation command specifies a service name other than MySQL following the —install option, the server uses that service name. It reads options from the [mysqld] group and the group that has the same name as the service in the standard option files. This enables you to use the [mysqld] group for options that should be used by all MySQL services, and an option group with the service name for use by the server installed with that service name.
If the service-installation command specifies a —defaults-file option after the service name, the server reads options the same way as described in the previous item, except that it reads options only from the named file and ignores the standard option files.
As a more complex example, consider the following command:
Here, the default service name ( MySQL ) is given after the —install option. If no —defaults-file option had been given, this command would have the effect of causing the server to read the [mysqld] group from the standard option files. However, because the —defaults-file option is present, the server reads options from the [mysqld] option group, and only from the named file.
On Windows, if the server is started with the —defaults-file and —install options, —install must be first. Otherwise, mysqld.exe attempts to start the MySQL server.
You can also specify options as Start parameters in the Windows Services utility before you start the MySQL service.
Finally, before trying to start the MySQL service, make sure the user variables %TEMP% and %TMP% (and also %TMPDIR% , if it has ever been set) for the operating system user who is to run the service are pointing to a folder to which the user has write access. The default user for running the MySQL service is LocalSystem , and the default value for its %TEMP% and %TMP% is C:\Windows\Temp , a directory LocalSystem has write access to by default. However, if there are any changes to that default setup (for example, changes to the user who runs the service or to the mentioned user variables, or the —tmpdir option has been used to put the temporary directory somewhere else), the MySQL service might fail to run because write access to the temporary directory has not been granted to the proper user.
Starting the service
After a MySQL server instance has been installed as a service, Windows starts the service automatically whenever Windows starts. The service also can be started immediately from the Services utility, or by using an sc start mysqld_service_name or NET START mysqld_service_name command. SC and NET commands are not case-sensitive.
When run as a service, mysqld has no access to a console window, so no messages can be seen there. If mysqld does not start, check the error log to see whether the server wrote any messages there to indicate the cause of the problem. The error log is located in the MySQL data directory (for example, C:\Program Files\MySQL\MySQL Server 8.0\data ). It is the file with a suffix of .err .
When a MySQL server has been installed as a service, and the service is running, Windows stops the service automatically when Windows shuts down. The server also can be stopped manually using the Services utility, the sc stop mysqld_service_name command, the NET START mysqld_service_name command, or the mysqladmin shutdown command.
You also have the choice of installing the server as a manual service if you do not wish for the service to be started automatically during the boot process. To do this, use the —install-manual option rather than the —install option:
Removing the service
To remove a server that is installed as a service, first stop it if it is running by executing SC STOP mysqld_service_name or NET STOP mysqld_service_name . Then use SC DELETE mysqld_service_name to remove it:
Alternatively, use the mysqld —remove option to remove the service.
If mysqld is not running as a service, you can start it from the command line. For instructions, see Section 2.3.4.6, “Starting MySQL from the Windows Command Line”.
For more information about stopping or removing a Windows service, see Section 5.8.2.2, “Starting Multiple MySQL Instances as Windows Services”.