Posted By: Mar. 12, 2020
How to check and repair MySQL Databases
You will need know how to check and repair MySQL databases or tables when you troubleshoot your website as they may have become corrupt. The mysqlcheck command is a maintenance tool that can be used to check, repair, analyze and optimize multiple tables from the command line. One of the best features of using mysqlcheck is that you don’t need to stop the MySQL service to perform the database maintenance.
In this tutorial, we will show you how to check/repair MySQL databases and tables.
Note : It is recommended to take a backup of your databases before performing a database repair operation.
Basic Syntax of mysqlcheck
A basic syntax of mysqlcheck is shown below:
mysqlcheck [OPTION] DATABASENAME TABLENAME -u root -p
A brief explanation of each option that you can use with mysqlcheck as shown below:
-c : Used to check a table for errors
-C : Used to check a tables that are changed after last week.
-a : Used to analyze tables.
-A : Used to check all databases.
-g : Used to check tables for version-dependent changes.
-B, –databases : Used to specify multiple databases.
-F : Used to check tables that are not closed properly.
–fix-db-names : Used to fix the database name.
–fix-table-names : Used to fix the table name.
–e : Used to perform an extended check.
-r : Used to repair corrupt table.
Check a Specific Table in a MySQL Database
In some cases, you need to check a specific table in a specific database. In that case, you can use the following syntax:
mysqlcheck -c databasename tablename -u root -p
For example, checks authors table in books database by running the following command:
mysqlcheck -c books authors -u root -p
You should get the following output:
books.authors OK
Check All Tables in a MySQL Database
If you want to check all the tables in a specific database use the following syntax:
mysqlcheck -c databasename -u root -p
For example, check all tables in books database by running the following command:
mysqlcheck -c books -u root -p
You should get the following output:
Enter password: books.accountant OK books.authors OK books.writer OK
Check and Optimize All Tables and All MySQL Databases
You can check all tables and all databases using the following command:
mysqlcheck -c -u root -p --all-databases
Output:
Enter password: books.accountant OK books.authors OK books.writer OK guest.MyGuests OK movies.netflix OK mysql.columns_priv OK mysql.component OK mysql.db OK mysql.default_roles OK mysql.engine_cost OK mysql.func OK mysql.general_log OK mysql.global_grants OK mysql.gtid_executed OK mysql.help_category OK mysql.help_keyword OK mysql.help_relation OK mysql.help_topic OK mysql.innodb_index_stats OK mysql.innodb_table_stats OK mysql.password_history OK mysql.plugin OK mysql.procs_priv OK mysql.proxies_priv OK mysql.role_edges OK mysql.server_cost OK mysql.servers OK mysql.slave_master_info OK mysql.slave_relay_log_info OK mysql.slave_worker_info OK
You can optimize all tables and all databases using the following command:
mysqlcheck -o root -p --all-databases
Output:
Enter password: books.accountant note : Table does not support optimize, doing recreate + analyze instead status : OK books.authors note : Table does not support optimize, doing recreate + analyze instead status : OK books.writer note : Table does not support optimize, doing recreate + analyze instead status : OK guest.MyGuests note : Table does not support optimize, doing recreate + analyze instead status : OK movies.netflix note : Table does not support optimize, doing recreate + analyze instead status : OK mysql.columns_priv note : Table does not support optimize, doing recreate + analyze instead status : OK mysql.component note : Table does not support optimize, doing recreate + analyze instead status : OK mysql.db note : Table does not support optimize, doing recreate + analyze instead status : OK mysql.default_roles note : Table does not support optimize, doing recreate + analyze instead status : OK mysql.engine_cost note : Table does not support optimize, doing recreate + analyze instead status : OK
In the above output, you should see “Table does not support optimize” which means the InnoDB table that doesn’t support this option.
Repair MySQL Databases
To repair accountant tables in books database run the following command:
mysqlcheck -r books accountant -u root -p
Output:
mysqlcheck -r books accountant -u root -p Enter password: books.accountant OK
To repair all tables in both books and movies database run the following command:
mysqlcheck -r --databases books movies -u root -p
Output:
Enter password: books.accountant OK books.authors OK books.writer OK movies.netflix OK
To check and repair all tables in all databases run the following command:
mysqlcheck --auto-repair --all-databases -u root -p
Output:
Enter password: books.accountant OK books.authors OK books.writer OK guest.MyGuests OK movies.netflix OK mysql.columns_priv OK mysql.component OK mysql.db OK mysql.default_roles OK mysql.engine_cost OK mysql.func OK mysql.general_log OK mysql.global_grants OK mysql.gtid_executed OK mysql.help_category OK mysql.help_keyword OK mysql.help_relation OK mysql.help_topic OK mysql.innodb_index_stats OK mysql.innodb_table_stats OK mysql.password_history OK mysql.plugin OK mysql.procs_priv OK mysql.proxies_priv OK mysql.role_edges OK mysql.server_cost OK mysql.servers OK mysql.slave_master_info OK mysql.slave_relay_log_info OK mysql.slave_worker_info OK mysql.slow_log OK mysql.tables_priv OK mysql.time_zone OK mysql.time_zone_leap_second OK mysql.time_zone_name OK mysql.time_zone_transition OK mysql.time_zone_transition_type OK
Important note: InnoDB storage engine does not support repair. So you will need to change MySQL storage engine from InnoDB to MyISAM.
Check, Repair and Optimize MySQL Database with PHPMyAdmin
You can also check, repair and optimize tables and databases using the PHPMyAdmin web interface.
You can follow the below steps to check, repair and optimize tables and databases:
1- Open the phpMyAdmin tool through a web browser as shown below:
2- Select the affected database in the left pane. You should see all the tables in the right pane in the following screen:
3- Click Check All to select all the tables. At the bottom of the window, choose Check Table from the menu. You should see a summary of the tables in the following screen:
4- To repair the table, Check All to select all the tables and choose Repair Table from the menu. You should see the following page:
Then you should get a confirmation that the command been executed successfully:
5- To optimize the table, Check All to select all the tables and choose Optimize Table from the menu. You should see the following page:
Then you should get a confirmation that the command been executed successfully:
Conclusion
In the above tutorial, we learned how to check and repair MySQL table using mysqlcheck command-line tool. We also learned how to check, repair and optimize database tables using the PHPMyAdmin web interface. I hope you can now easily fix your corrupted tables using this tool.
mariadb-check
is a tool for checking, repairing, analyzing and optimizing tables.
MariaDB starting with 10.4.6
From MariaDB 10.4.6, mariadb-check
is a symlink to mysqlcheck, the old name for the tool
.
MariaDB starting with 10.5.2
From MariaDB 10.5.2, mariadb-check
is the name of the tool, with mysqlcheck
a symlink .
See mariadb-check for details.
- ← Installing System Tables (mariadb-install-db)
- ↑ Table Statements ↑
- mysql_upgrade →
Comments
Comments loading…
Content reproduced on this site is the property of its respective owners,
and this content is not reviewed in advance by MariaDB. The views, information and opinions
expressed by this content do not necessarily represent those of MariaDB or any other party.
Одной из ярких причин возникновения ошибок в базе данных может послужить неправильная остановка сервера MySQL. Как это обычно бывает, сбой в электропитании сервера, либо иные причины, повлекшие за собой банальное отключение машины, либо перезагрузку. Иногда, и нередко подобного рода сбои могут повлечь за собой проблемы, которые решаются лишь путем восстановления данных из бэкапа, и это к вопросу для чего нужно делать бэкапы. Наличие ошибок в базе данных может проявиться не сразу, однако если они есть, то вы их рано или поздно обязательно заметите. Проблемы, как правило, проявляются в виде ошибок после запросов к базе, либо база начинает уходить в раздумье на не свойственное для этого время.
Давайте посмотрим, что можно предпринять первым делом, чтобы попытаться исправить ситуацию. Утилита mysqlcheck как правило устанавливается по умолчанию с сервером MySQL может быть использована для проверки баз данных на ошибки. Рассмотрим пример ее использования.
Использование утилиты mysqlcheck
# mysqlcheck -u root -p --optimize --auto-repair --all-databases
Назначение параметров:
--optimize – Оптимизируем все базы. --auto-repair – Ремонтируем все базы. --all-databases – Проверяем ошибки у всех баз.
Если база данных больших размеров, а вам нужно срочно поправить определенную таблицу, то вы можете запустить проверку определенной таблицы в базе данных.
Проверка отдельной таблицы в базе данных:
# mysqlcheck -r имя_базы имя_таблицы_в_базе -u root -p
Исправление таблиц MyISAM.
Так же существует утилита myisamchk, отличается от предыдущей утилиты тем, что перед её использованием необходимо останавливать сервер баз данных, в то время как mysqlcheck может использоваться при работающем сервере. Рассмотрим пример использования утилиты myisamchk.
Останавливаем сервер MySQL
# service mysqld stop
Анализируем базу данных на наличие ошибок
# myisamchk -s /var/db/mysql/наша_база/*.MYI
Обратите внимание, что путь к базам данных у вас может отличаться, этот момент вам следует так же уточнить. Если есть ошибки, то появиться сообщение подобного вида:
myisamchk: warning: 2 client is using or hasn't closed the table properly MyISAM-table '/var/db/mysql/наша_база/ary_mem.MYI' is usable but should be fixed
Исправляем ошибки с помощью myisamchk
# myisamchk -r /var/db/mysql/наша_база/ary_mem.MYI
Исправляем ошибки по всем таблицам в базе (рекурсивно)
# myisamchk -r /var/db/mysql/наша_база/*.MYI
Процесс исправления ошибок будет сопровождаться подобным выводом сообщений в окне консоли:
- Fixing index 1 - Fixing index 2 - Fixing index 3
После того как ошибки исправлены, можно запустить сервер MySQL, чтобы убедиться что всё в порядке.
Запуск сервера MySQL
# service mysqld start
Хотелось бы отметить один момент, что команды остановки и запуска сервера MySQL, а так же пути расположения баз данных на вашем сервере могут отличаться, поэтому вам так же следует эти моменты учесть.
One of the clearest reasons for errors in the database can be an improper shutdown of the MySQL server. As it usually happens, there is a power failure of the server, or other reasons that led to a banal shutdown of the machine, or a reboot. Sometimes, and often, this kind of failure can lead to problems that can be solved only by restoring data from a backup, and this is the question of why you need to make backups . The presence of errors in the database may not appear immediately, but if they are, then sooner or later you will definitely notice them. Problems, as a rule, manifest themselves in the form of errors after queries to the database, or the database begins to go into thought for an inappropriate time.
Let’s see what you can do first to try to fix the situation. The mysqlcheck
utility is usually installed by default with the MySQL server and can be used to check databases for errors. Let’s consider an example of its use.
Using the mysqlcheck utility
# mysqlcheck -u root -p --optimize --auto-repair --all-databases
Purpose of parameters:
1 2 3 |
|
If the database is large, and you urgently need to correct a specific table, then you can run a check of a specific table in the database.
Checking a single table in the database:
# mysqlcheck -r DB_name Table_name -u root -p
Correction of MyISAM tables
There is also the myisamchk utility , which differs from the previous utility in that before using it, you must stop the database server, while mysqlcheck can be used when the server is running. Let’s look at an example of using the myisamchk utility.
Stopping MySQL Server
Analyzing the database for errors
# myisamchk -s /var/db/mysql/our_database/*.MYI
Please note that the path to the databases may differ for you, you should also clarify this point. If there are errors, then a message similar to the following will appear:
myisamchk: warning: 2 client is using or hasn't closed the table properly
MyISAM-table '/var/db/mysql/our_database/ary_mem.MYI' is usable but should be fixed
Correcting errors with myisamchk
# myisamchk -r /var/db/mysql/our_database/ary_mem.MYI
We fix errors for all tables in the database (recursively)
# myisamchk -r /var/db/mysql/our_database/*.MYI
The error correction process will be accompanied by a similar message output in the console window:
1 2 3 |
|
After the bugs are fixed, you can start the MySQL server to make sure everything is in order.
Starting the MySQL Server
I would like to note one point that the commands for stopping and starting the MySQL server, as well as the paths for the location of the databases on your server, may differ, so you should also take these points into account.
Вас заинтересует / Intresting for you:
When your mysql table gets corrupted, use mysqlcheck command to repair it.
Mysqlcheck command checks, repairs, optimizes and analyzes the tables.
1. Check a Specific Table in a Database
If your application gives an error message saying that a specific table is corrupted, execute the mysqlcheck command to check that one table.
The following example checks employee table in thegeekstuff database.
# mysqlcheck -c thegeekstuff employee -u root -p Enter password: thegeekstuff.employee OK
You should pass the username/password to the mysqlcheck command. If not, you’ll get the following error message.
# mysqlcheck -c thegeekstuff employee mysqlcheck: Got error: 1045: Access denied for user 'root'@'localhost' (using password: NO) when trying to connect
Please note that myisamchk command that we discussed a while back works similar to the mysqlcheck command. However, the advantage of mysqlcheck command is that it can be executed when the mysql daemon is running. So, using mysqlcheck command you can check and repair corrupted table while the database is still running.
2. Check All Tables in a Database
To check all the tables in a particular database, don’t specify the table name. Just specify the database name.
The following example checks all the tables in the alfresco database.
# mysqlcheck -c alfresco -u root -p Enter password: alfresco.JBPM_ACTION OK alfresco.JBPM_BYTEARRAY OK alfresco.JBPM_BYTEBLOCK OK alfresco.JBPM_COMMENT OK alfresco.JBPM_DECISIONCONDITIONS OK alfresco.JBPM_DELEGATION OK alfresco.JBPM_EVENT OK ..
3. Check All Tables and All Databases
To check all the tables and all the databases use the “–all-databases” along with -c option as shown below.
# mysqlcheck -c -u root -p --all-databases Enter password: thegeekstuff.employee OK alfresco.JBPM_ACTION OK alfresco.JBPM_BYTEARRAY OK alfresco.JBPM_BYTEBLOCK OK .. .. mysql.help_category error : Table upgrade required. Please do "REPAIR TABLE `help_category`" or dump/reload to fix it! mysql.help_keyword error : Table upgrade required. Please do "REPAIR TABLE `help_keyword`" or dump/reload to fix it! ..
If you want to check all tables of few databases, specify the database names using “–databases”.
The following example checks all the tables in thegeekstuff and alfresco database.
# mysqlcheck -c -u root -p --databases thegeekstuff alfresco Enter password: thegeekstuff.employee OK alfresco.JBPM_ACTION OK alfresco.JBPM_BYTEARRAY OK alfresco.JBPM_BYTEBLOCK OK ..
4. Analyze Tables using Mysqlcheck
The following analyzes employee table that is located in thegeekstuff database.
# mysqlcheck -a thegeekstuff employee -u root -p Enter password: thegeekstuff.employee Table is already up to date
Internally mysqlcheck command uses “ANALYZE TABLE” command. While mysqlcheck is executing the analyze command the table is locked and available for other process only in the read mode.
5. Optimize Tables using Mysqlcheck
The following optimizes employee table that is located in thegeekstuff database.
# mysqlcheck -o thegeekstuff employee -u root -p Enter password: thegeekstuff.employee OK
Internally mysqlcheck command uses “OPTIMIZE TABLE” command. When you delete lot of rows from a table, optimizing it helps to get the unused space and defragment the data file. This might improve performance on huge tables that has gone through several updates.
6. Repair Tables using Mysqlcheck
The following repairs employee table that is located in thegeekstuff database.
# mysqlcheck -r thegeekstuff employee -u root -p Enter password: thegeekstuff.employee OK
Internally mysqlcheck command uses “REPAIR TABLE” command. This will repair and fix a corrupted MyISAM and archive tables.
7. Combine Check, Optimize, and Repair Tables
Instead of checking and repairing separately. You can combine check, optimize and repair functionality together using “–auto-repair” as shown below.
The following checks, optimizes and repairs all the corrupted table in thegeekstuff database.
# mysqlcheck -u root -p --auto-repair -c -o thegeekstuff
You an also check, optimize and repair all the tables across all your databases using the following command.
# mysqlcheck -u root -p --auto-repair -c -o --all-databases
If you want to know what the command is doing while it is checking, add the –debug-info as shown below. This is helpful while you are checking a huge table.
# mysqlcheck --debug-info -u root -p --auto-repair -c -o thegeekstuff employee Enter password: thegeekstuff.employee Table is already up to date User time 0.00, System time 0.00 Maximum resident set size 0, Integral resident set size 0 Non-physical pagefaults 344, Physical pagefaults 0, Swaps 0 Blocks in 0 out 0, Messages in 0 out 0, Signals 0 Voluntary context switches 12, Involuntary context switches 9
8. Additional Useful Mysqlcheck Options
The following are some of the key options that you can use along with mysqlcheck.
- -A, –all-databases Consider all the databases
- -a, –analyze Analyze tables
- -1, –all-in-1 Use one query per database with tables listed in a comma separated way
- –auto-repair Repair the table automatically it if is corrupted
- -c, –check Check table errors
- -C, –check-only-changed Check tables that are changed since last check
- -g, –check-upgrade Check for version dependent changes in the tables
- -B, –databases Check more than one databases
- -F, –fast Check tables that are not closed properly
- –fix-db-names Fix DB names
- –fix-table-names Fix table names
- -f, –force Continue even when there is an error
- -e, –extended Perform extended check on a table. This will take a long time to execute.
- -m, –medium-check Faster than extended check option, but does most checks
- -o, –optimize Optimize tables
- -q, –quick Faster than medium check option
- -r, –repair Fix the table corruption