Search the MySQL manual:
MySQL Manual

Buy this Reference Manual in softcover from Barnes & Noble!

/ / Up / Table of Contents

A.2.2 Ошибка MySQL server has gone away

Все изложенное в данном разделе относится также и к родственной ошибке Lost connection to server during query.

Наиболее часто ошибка MySQL server has gone away возникает в результате тайм-аута соединения и его закрытия сервером. По умолчанию сервер закрывает соединение по прошествии 8 часов бездействия. Можно изменить лимит времени, установив при запуске mysqld переменную wait_timeout.

Другой распространенной причиной получения ошибки MySQL server has gone away является выдача команды "закрытия" на соединении MySQL с последующей попыткой выполнить запрос на закрытом соединении.

Если это получено в скрипте, то достаточно просто повторить запрос от клиента, чтобы соединение автоматически восстановилось.

Обычно в этом случае выдаются следующие коды ошибки (какой из них вы получите, зависит от ОС):

Код ошибки Описание
CR_SERVER_GONE_ERROR Клиент не может послать запрос серверу.
CR_SERVER_LOST Клиент не получил ошибки при передаче запроса серверу, но он не получил также полного ответа (или хоть какого-то ответа) на запрос.

Ошибка будет также выдана, если кто-нибудь уничтожит выполняющийся поток посредством kill номерпотока.

Проверить, что MySQL на ходу, можно, запустив mysqladmin version и изучив время работы (uptime). Если проблема в аварийном завершении mysqld, то необходимо сосредоточиться на поиске причины аварии. В этом случае следует сначала проверить, не будет ли уничтожен MySQL снова при повторном задании запроса (see section A.4.1 Что делать, если работа MySQL сопровождается постоянными сбоями).

Эти ошибки будут также выдаваться при посылке серверу неверного или слишком длинного запроса. Если mysqld получает неправильный или слишком большой пакет, то сервер предполагает, что с клиентом что-то не так, и закрывает соединение. Если необходимо выполнять объемные запросы (например, при работе с большими столбцами типа BLOB), можно увеличить предельный размер запроса, запустив mysqld с опцией -O max_allowed_packet=# (по умолчанию 1 Mб). Дополнительная память выделяется по требованию, так что mysqld будет использовать больше памяти только в случае, когда выдан большой запрос или когда mysqld должен возвратить большую строку результата!

Если у вас возникнет желание сделать отчет об ошибке по этой проблеме, то не забудьте включить в него следующие сведения:

Обращайтесь к разделу See section 1.8.1.2 Как задавать вопросы и направлять сообщения об ошибках.

User Comments

Posted by on Friday May 17 2002, @6:24am [Delete] [Edit]

If you keep getting:
error: 'Can't connect to local MySQL server
through socket '/tmp/mysql.sock' (2)'

Some RPM's put the mysql.sock file
in /var/lib/mysql/mysql.sock instead
of /tmp/mysql.sock
I was pulling my hair out for ages over this!
Small hack is to symlink it:
"ln -s /var/lib/mysql/mysql.sock /tmp"

Posted by [name withheld] on Friday May 17 2002, @6:24am [Delete] [Edit]

After a lot of investigation on how to manage
MySql server crashs i
set up a hourly cron script that will check if
mysql daemon is running
and if not will restart apache automaticaly.
This script is running in my server now and its
doing great.


# Begin Script
#!/bin/sh
#
# Stay alive crontab script:
#
if test -f "/var/lib/mysql/mysqld.pid"; then
echo "/var/lib/mysql/mysqld.pid" exist
else
echo "/var/lib/mysql/mysqld.pid" does not
exist
shutdown -r now > /dev/null
fi
exit 0
# End Script

Posted by [name withheld] on Friday May 17 2002, @6:24am [Delete] [Edit]

This is a quick minor correction to the previous
comment. The author talks about a script
that "restarts apache" - when he is actually
restarting MySql.

Posted by Gil Caseiro on Friday May 17 2002, @6:24am [Delete] [Edit]

Bei Puretec Datenbanken ist es notwendig in der Zeile $cfgServers[1]['port'] = '';
als Port 3306 einzugeben. Also: $cfgServers[1]['port'] = '3306';

Posted by on Wednesday December 18 2002, @5:29pm [Delete] [Edit]

babelfish.altavista.com: With Puretec
data bases it is necessary in the line
$$cfgServers[1]['port ' ] = ' '; to enter as
haven 3306. Thus: $$cfgServers[1]['port ' ] =
' 3306';

Posted by Michael Bagley on Friday May 17 2002, @6:24am [Delete] [Edit]

I'm running Red Hat 7.2 and tried the symlink
approach to repairing this problem with no
success. I am curios as to what I beleive is the
German's sugestion, but I am unable to translate
the suggestion.

Posted by [name withheld] on Friday June 7 2002, @5:11pm [Delete] [Edit]

For those amongst us unfortunate enough to run
MySQL on windows 2000:
If you can't get the service to start, configure
your my.ini script to use innodb and set some
normal params as described in the manual
elsewhere.
Run "MySQLd --skip-name-resolve" from the command
prompt. When innodb has started you can login to
your database with root, even though the MySQL
service doesn't appear to be started. You can now
use your database as you see fit. Also, you don't
have to try to start the service once you've done
the above, because that won't work anyway.
This worked for me on Windows 2000 SBS (yes you
can laugh at me), but I'm not sure weither this
is the solution for everyone...
[email protected]

Posted by on Thursday September 26 2002, @3:55pm [Delete] [Edit]

I have a problem with a Perl Script that keeps
sending me the nex error "DBD::mysql::st execute
failed: MySQL server has gone away at path to
archive " but the script sometimes works and others
no I hope someone can help me with this problem

Posted by on Saturday October 5 2002, @1:58pm [Delete] [Edit]

Here's something that others might run across
which I haven't
seen mentioned on this site elsewhere.

I was suddenly getting server restarts and 'server
has gone
away' errors from one of the hosts that processes
data on
my mysqld database. There were two other hosts which
were running just fine. Rebuilding the indices
with myisamchk
took a long time, but didn't fix the problem.

The problem turned out to be caused by a lack of
reverse
name lookups in DNS for the ip of the clients.
Somehow
the dns server listed in /etc/resolv.conf had
stopped doing
reverse lookup resolution for the zone these
clients were in.
Some of the hosts were listed in /etc/hosts --
those were
the ones that were working.

Simply adding the hostnames to /etc/hosts with the
correct
ip addresses was enough to get mysqld and the
client working
normally again.

The dns server has since been fixed as well to manage
the reverse zone for the client network as expected by
mysqld.


This is interesting because the error has nothing
to do
with a network timeout as was described in the other
messages.

I dont know if it would have helped, but there was
nothing
logged in the error log for mysqld saying that it
failed
because of the ip address lookup.

Posted by on Thursday January 2 2003, @8:07pm [Delete] [Edit]

I tried to run "mysqldump -A" for backup purposes (mysqldump -A -p > backup.sql).After that I got the "Lost Connection to MySQL server during query" error. I search in many mailing list about this error and find that I need to downgrade a glibc of my red hat Linux. I do that but MySQL return the same error. So I tried to run "mysqldump -A" with "nice -20" (highest priority) to see if the problem is some kind of timeout in mysqldump connection. It's amazing but the error is gone. The complete command was "nice --20 mysqldump -A -p > backup.sql".

Add your own comment.

Top / / / Up / Table of Contents