Mysql код ошибки 2006

I have encountered this a number of times and I’ve normally found the answer to be a very low default setting of max_allowed_packet.

Raising it in /etc/my.cnf (under [mysqld]) to 8 or 16M usually fixes it. (The default in MySql 5.7 is 4194304, which is 4MB.)

[mysqld]
max_allowed_packet=16M

Note: Just create the line if it does not exist, it must appear as an entry underneath [mysqld]

Note: This can be set on your server as it’s running but it will be lost after the mysql daemon is restarted. Use SET GLOBAL max_allowed_packet=104857600 (this sets it to 100MB)

Note: On Windows you may need to save your my.ini or my.cnf file with ANSI not UTF-8 encoding.

answered Feb 28, 2012 at 9:48

George's user avatar

GeorgeGeorge

4,9062 gold badges16 silver badges21 bronze badges

16

I had the same problem but changeing max_allowed_packet in the my.ini/my.cnf file under [mysqld] made the trick.

add a line

max_allowed_packet=500M

now restart the MySQL service once you are done.

answered Oct 17, 2013 at 11:51

Sathish D's user avatar

Sathish DSathish D

4,85431 silver badges44 bronze badges

3

I used following command in MySQL command-line to restore a MySQL database which size more than 7GB, and it works.

set global max_allowed_packet=268435456;

Michał Perłakowski's user avatar

answered Feb 24, 2016 at 10:31

Geshan Ravindu's user avatar

3

It may be easier to check if the connection exists and re-establish it if needed.

See PHP:mysqli_ping for info on that.

Community's user avatar

answered Oct 29, 2011 at 23:15

Niet the Dark Absol's user avatar

4

There are several causes for this error.

MySQL/MariaDB related:

  • wait_timeout — Time in seconds that the server waits for a connection to become active before closing it.
  • interactive_timeout — Time in seconds that the server waits for an interactive connection.
  • max_allowed_packet — Maximum size in bytes of a packet or a generated/intermediate string. Set as large as the largest BLOB, in multiples of 1024.

Example of my.cnf:

[mysqld]
# 8 hours
wait_timeout = 28800
# 8 hours
interactive_timeout = 28800
max_allowed_packet = 256M

Server related:

  • Your server has full memory — check info about RAM with free -h

Framework related:

  • Check settings of your framework. Django for example use CONN_MAX_AGE (see docs)

How to debug it:

  • Check values of MySQL/MariaDB variables.
    • with sql: SHOW VARIABLES LIKE '%time%';
    • command line: mysqladmin variables
  • Turn on verbosity for errors:
    • MariaDB: log_warnings = 4
    • MySQL: log_error_verbosity = 3
  • Check docs for more info about the error

answered Feb 21, 2019 at 9:48

jozo's user avatar

jozojozo

4,2421 gold badge28 silver badges29 bronze badges

Error: 2006 (CR_SERVER_GONE_ERROR)

Message: MySQL server has gone away

Generally you can retry connecting and then doing the query again to solve this problem — try like 3-4 times before completely giving up.

I’ll assuming you are using PDO. If so then you would catch the PDO Exception, increment a counter and then try again if the counter is under a threshold.

If you have a query that is causing a timeout you can set this variable by executing:

SET @@GLOBAL.wait_timeout=300;
SET @@LOCAL.wait_timeout=300;  -- OR current session only

Where 300 is the number of seconds you think the maximum time the query could take.

Further information on how to deal with Mysql connection issues.

EDIT: Two other settings you may want to also use is net_write_timeout and net_read_timeout.

answered Oct 29, 2011 at 23:22

Yzmir Ramirez's user avatar

In MAMP (non-pro version) I added

--max_allowed_packet=268435456

to ...\MAMP\bin\startMysql.sh

Credits and more details here

icedwater's user avatar

icedwater

4,7013 gold badges35 silver badges50 bronze badges

answered Feb 29, 2012 at 17:00

uwe's user avatar

uweuwe

3,93711 gold badges37 silver badges50 bronze badges

0

If you are using xampp server :

Go to xampp -> mysql -> bin -> my.ini

Change below parameter :

max_allowed_packet = 500M

innodb_log_file_size = 128M

This helped me a lot :)

answered Aug 3, 2019 at 8:32

Archana Kamath's user avatar

1

I was getting this same error on my DigitalOcean Ubuntu server.

I tried changing the max_allowed_packet and the wait_timeout settings but neither of them fixed it.

It turns out that my server was out of RAM. I added a 1GB swap file and that fixed my problem.

Check your memory with free -h to see if that’s what’s causing it.

answered Sep 19, 2016 at 23:45

Pikamander2's user avatar

Pikamander2Pikamander2

7,3923 gold badges48 silver badges69 bronze badges

1

On windows those guys using xampp should use this path xampp/mysql/bin/my.ini and change max_allowed_packet(under section[mysqld])to your choice size.
e.g

max_allowed_packet=8M

Again on php.ini(xampp/php/php.ini) change upload_max_filesize the choice size.
e.g

upload_max_filesize=8M

Gave me a headache for sometime till i discovered this. Hope it helps.

answered Oct 16, 2015 at 16:02

Kenneth mwangi's user avatar

3

It was RAM problem for me.

I was having the same problem even on a server with 12 CPU cores and 32 GB RAM. I researched more and tried to free up RAM. Here is the command I used on Ubuntu 14.04 to free up RAM:

sync && echo 3 | sudo tee /proc/sys/vm/drop_caches

And, it fixed everything. I have set it under cron to run every hour.

crontab -e

0 * * * * bash /root/ram.sh;

And, you can use this command to check how much free RAM available:

free -h

And, you will get something like this:

             total       used       free     shared    buffers     cached
Mem:           31G        12G        18G        59M       1.9G       973M
-/+ buffers/cache:       9.9G        21G
Swap:         8.0G       368M       7.6G

answered Mar 26, 2017 at 5:38

Rehmat's user avatar

RehmatRehmat

2,1312 gold badges24 silver badges28 bronze badges

In my case it was low value of open_files_limit variable, which blocked the access of mysqld to data files.

I checked it with :

mysql> SHOW VARIABLES LIKE 'open%';
+------------------+-------+
| Variable_name    | Value |
+------------------+-------+
| open_files_limit | 1185  |
+------------------+-------+
1 row in set (0.00 sec)

After I changed the variable to big value, our server was alive again :

[mysqld]
open_files_limit = 100000

answered Sep 8, 2016 at 14:31

Fedir RYKHTIK's user avatar

Fedir RYKHTIKFedir RYKHTIK

9,8546 gold badges58 silver badges68 bronze badges

This generally indicates MySQL server connectivity issues or timeouts.
Can generally be solved by changing wait_timeout and max_allowed_packet in my.cnf or similar.

I would suggest these values:

wait_timeout = 28800

max_allowed_packet = 8M

answered Jun 29, 2018 at 14:35

Memo's user avatar

MemoMemo

911 gold badge2 silver badges12 bronze badges

If you are using the 64Bit WAMPSERVER, please search for multiple occurrences of max_allowed_packet because WAMP uses the value set under [wampmysqld64] and not the value set under [mysqldump], which for me was the issue, I was updating the wrong one. Set this to something like max_allowed_packet = 64M.

Hopefully this helps other Wampserver-users out there.

answered Mar 14, 2018 at 14:54

Enomatix24's user avatar

Enomatix24Enomatix24

1561 silver badge7 bronze badges

0

There is an easier way if you are using XAMPP.
Open the XAMPP control panel, and click on the config button in mysql section.
enter image description here

Now click on the my.ini and it will open in the editor. Update the max_allowed_packet to your required size.

enter image description here

Then restart the mysql service. Click on stop on the Mysql service click start again. Wait for a few minutes.
enter image description here
enter image description here

Then try to run your Mysql query again. Hope it will work.

answered May 5, 2019 at 5:44

Hriju's user avatar

HrijuHriju

7281 gold badge16 silver badges27 bronze badges

It’s always a good idea to check the logs of the Mysql server, for the reason why it went away.

It will tell you.

answered Jun 30, 2018 at 18:06

Alex's user avatar

AlexAlex

32.7k17 gold badges107 silver badges172 bronze badges

MAMP 5.3, you will not find my.cnf and adding them does not work as that max_allowed_packet is stored in variables.

One solution can be:

  1. Go to http://localhost/phpmyadmin
  2. Go to SQL tab
  3. Run SHOW VARIABLES and check the values, if it is small then run with big values
  4. Run the following query, it set max_allowed_packet to 7gb:

    set global max_allowed_packet=268435456;

For some, you may need to increase the following values as well:

set global wait_timeout = 600;
set innodb_log_file_size =268435456;

answered May 9, 2019 at 20:47

Rupak Nepali's user avatar

Rupak NepaliRupak Nepali

7191 gold badge6 silver badges13 bronze badges

For Vagrant Box, make sure you allocate enough memory to the box

config.vm.provider "virtualbox" do |vb|
  vb.memory = "4096"
end

answered Dec 13, 2015 at 8:39

Shadoweb's user avatar

ShadowebShadoweb

5,8321 gold badge42 silver badges55 bronze badges

0

This might be a problem of your .sql file size.

If you are using xampp. Go to the xampp control panel -> Click MySql config -> Open my.ini.

Increase the packet size.

max_allowed_packet = 2M -> 10M

answered Jan 10, 2018 at 11:43

Nikunj Dhimar's user avatar

The unlikely scenario is you have a firewall between the client and the server that forces TCP reset into the connection.

I had that issue, and I found our corporate F5 firewall was configured to terminate inactive sessions that are idle for more than 5 mins.

Once again, this is the unlikely scenario.

answered May 23, 2017 at 18:36

Ahmed's user avatar

AhmedAhmed

2,8251 gold badge25 silver badges39 bronze badges

uncomment the ligne below in your my.ini/my.cnf, this will split your large file into smaller portion

# binary logging format - mixed recommended
# binlog_format=mixed

TO

# binary logging format - mixed recommended
binlog_format=mixed

answered Sep 25, 2015 at 14:30

Nico's user avatar

1

I found the solution to «#2006 — MySQL server has gone away» this error.
Solution is just you have to check two files

  1. config.inc.php
  2. config.sample.inc.php

Path of these files in windows is

C:\wamp64\apps\phpmyadmin4.6.4

In these two files the value of this:

$cfg['Servers'][$i]['host']must be 'localhost' .

In my case it was:

$cfg['Servers'][$i]['host'] = '127.0.0.1';

change it to:

"$cfg['Servers'][$i]['host']" = 'localhost';

Make sure in both:

  1. config.inc.php
  2. config.sample.inc.php files it must be ‘localhost’.

And last set:

$cfg['Servers'][$i]['AllowNoPassword'] = true;

Then restart Wampserver.


To change phpmyadmin user name and password

You can directly change the user name and password of phpmyadmin through config.inc.php file

These two lines

$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '';

Here you can give new user name and password.
After changes save the file and restart WAMP server.

answered Jun 10, 2017 at 8:18

um life's user avatar

I got Error 2006 message in different MySQL clients software on my Ubuntu desktop. It turned out that my JDBC driver version was too old.

answered Jun 16, 2017 at 15:58

Bo Guo's user avatar

Bo GuoBo Guo

1013 bronze badges

I had the same problem in docker adding below setting in docker-compose.yml:

db:
    image: mysql:8.0
    command: --wait_timeout=800 --max_allowed_packet=256M --character-set-server=utf8 --collation-server=utf8_general_ci --default-authentication-plugin=mysql_native_password
    volumes:
      - ./docker/mysql/data:/var/lib/mysql
      - ./docker/mysql/dump:/docker-entrypoint-initdb.d
    ports:
      - 3306:3306
    environment:
      MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
      MYSQL_DATABASE: ${MYSQL_DATABASE}
      MYSQL_USER: ${MYSQL_USER}
      MYSQL_PASSWORD: ${MYSQL_PASSWORD}

answered Nov 11, 2020 at 17:14

Dmitry Leiko's user avatar

Dmitry LeikoDmitry Leiko

3,9803 gold badges25 silver badges42 bronze badges

1

I also encountered this error. But even with the increased max_allowed_packet or any increase of value in the my.cnf, the error still persists.

What I did is I troubleshoot my database:

  • I checked the tables where the error persists
  • Then I checked each row
  • There are rows that are okay to fetch and there are rows where the error only shows up
  • It seems that there are value in these rows that is causing this error
  • But even by selecting only the primary column, the error still shows up (SELECT primary_id FROM table)

The solution that I thought of is to reimport the database. Good thing is I have a backup of this database. But I only dropped the problematic table, then import my backup of this table. That solved my problem.


My takeaway of this problem:

  • Always have a backup of your database. Either manually or thru CRON job
  • I noticed that there are special characters in the affected rows. So when I recovered the table, I immediately changed the collation of this table from latin1_swedish_ci to utf8_general_ci
  • My database was working fine before then my system suddenly encountered this problem. Maybe it also has something to do with the upgrade of the MySQL database by our hosting provider. So frequent backup is a must!

answered May 3, 2021 at 1:49

Logan Wayne's user avatar

Logan WayneLogan Wayne

6,00116 gold badges31 silver badges49 bronze badges

Just in case this helps anyone:

I got this error when I opened and closed connections in a function which would be called from several parts of the application.
We got too many connections so we thought it might be a good idea to reuse the existing connection or throw it away and make a new one like so:

public static function getConnection($database, $host, $user, $password){
    if (!self::$instance) {
        return self::newConnection($database, $host, $user, $password);
    } elseif ($database . $host . $user != self::$connectionDetails) {
        self::$instance->query('KILL CONNECTION_ID()');
        self::$instance = null;
        return self::newConnection($database, $host, $user, $password);
    }
    return self::$instance;
}

Well turns out we’ve been a little too thorough with the killing and so the processes doing important things on the old connection could never finish their business.
So we dropped these lines

self::$instance->query('KILL CONNECTION_ID()');
self::$instance = null;

and as the hardware and setup of the machine allows it we increased the number of allowed connections on the server by adding

max_connections = 500

to our configuration file. This fixed our problem for now and we learned something about killing mysql connections.

masud_moni's user avatar

answered May 20, 2020 at 7:10

Max's user avatar

MaxMax

2,5611 gold badge24 silver badges29 bronze badges

For users using XAMPP, there are 2 max_allowed_packet parameters in C:\xampp\mysql\bin\my.ini.

answered Jun 26, 2018 at 12:10

Subhash's user avatar

SubhashSubhash

1781 silver badge9 bronze badges

This error happens basically for two reasons.

  1. You have a too low RAM.
  2. The database connection is closed when you try to connect.

You can try this code below.

# Simplification to execute an SQL string of getting a data from the database
def get(self, sql_string, sql_vars=(), debug_sql=0):
    try:            
        self.cursor.execute(sql_string, sql_vars)
        return self.cursor.fetchall()
    except (AttributeError, MySQLdb.OperationalError):
        self.__init__()
        self.cursor.execute(sql_string, sql_vars)
        return self.cursor.fetchall()

It mitigates the error whatever the reason behind it, especially for the second reason.

If it’s caused by low RAM, you either have to raise database connection efficiency from the code, from the database configuration, or simply raise the RAM.

answered Sep 21, 2018 at 10:54

Aminah Nuraini's user avatar

Aminah NurainiAminah Nuraini

18.2k9 gold badges90 silver badges109 bronze badges

1

For me it helped to fix one’s innodb table’s corrupted index tree. I localized such a table by this command

mysqlcheck -uroot --databases databaseName 

result

mysqlcheck: Got error: 2013: Lost connection to MySQL server during query when executing 'CHECK TABLE ...

as followed I was able to see only from the mysqld logs /var/log/mysqld.log which table was causing troubles.

FIL_PAGE_PREV links 2021-08-25T14:05:22.182328Z 2 [ERROR] InnoDB: Corruption of an index tree: table `database`.`tableName` index `PRIMARY`, father ptr page no 1592, child page no 1234'

The mysqlcheck command did not fix it, but helped to unveil it.
Ultimately I fixed it as followed by a regular mysql command from a mysql cli

OPTIMIZE table theCorruptedTableNameMentionedAboveInTheMysqld.log

answered Aug 25, 2021 at 16:04

FantomX1's user avatar

FantomX1FantomX1

1,5952 gold badges15 silver badges23 bronze badges

Ошибка 2006 под названием MySQL Sever has gone away означает отказ сервера в соединении даже при условии, что он запущен. Известно всего три причины, почему ошибка появляется. Первая причина – сервер перегружен. Время ожидания истекло. Вторая причина – клиент отправил слишком больной пакет. Третья – сервер не был до конца проинициализирован. Дальше подробно рассмотрим, по каким причинам появляется ошибка и как с ней бороться.

Как исправить ошибку

Обычно ошибка появляется при попытке подключиться к базе данных при помощи PHP, консольного клиента, а также в случае использования PhpMyAdmin:

PhpMyAdmin

Давайте дальше рассмотрим каждую ситуацию в отдельности.

Истекло время ожидания

Как было сказано в начале статьи, одна из возможных причин – истечение времени ожидания. Может быть так, что сервер был перегружен и не справляется с нагрузкой – обработкой всех соединений. Чтобы понять, насколько долго выполняются серверные запросы, можно воспользоваться любым консольным клиентом и подключиться к серверу. Если вам удастся это сделать, выполните любой запрос. Если на обработку запросов уходит слишком много времени, оптимизировать  MySQL можно при помощи специального скрипта MySQLTuner. Обычно увеличивается размер пула движка InnoDB путем установки параметра innodb_buffer_pool_size. Оптимальное значение определяется при помои приведенного выше скрипта.

Если это 800 мегабайт (может быть и другой размер), прописываем:

$ sudo vi /etc/mysql/my.cnf

innodb_buffer_pool_size=800M

https://pq.hosting/help/myfiles/mysqlhasgoneavay-991x576.png

Существует и другой способ решения проблемы. Для этого увеличивают время ответа от сервера. Чтобы выполнить эту задачу, необходимо изменить параметр wait_timeout. Это время в секундах, на протяжении которого надо ждать ответа от сервера.

Например:

wait_timeout=500

параметр wait_timeout

Внося изменения, не забываем дальше перезагрузить сервер:

$ sudo systemctl restart mysql

или:

$ sudo systemctl restart mariadb

Слишком большой пакет

Когда клиент пользователя создает слишком большое количество пакетов, сервер выдаст именно эту ошибку. Доступный размер пакета (максимальное значение) можно увеличить с помощью параметра max_allowed_packet.

Например:

$ sudo vi /etc/mysql/my.cnf

max_allowed_packet=128M

Отдельно обратите внимание на клиент, ведь если он посылает много запросов, то вы явно что-то делает не так. Как минимум не стоит генерировать запросы к MySQL с помощью циклов for.

Сервер неверно проинициализирован

Если вы решите развернуть MySQL или MariaDB в Docker, то будьте готовы столкнуться с подобной ошибкой. Первоначальная инициализация контейнера требует чуть больше свободного времени. Если не дать контейнеру завершить инициализацию, сперва остановив его и запустив, то база данных будет всегда возвращать такую ошибку. Решение – нужно полностью удалить данные контейнера с базой данных.

Делается это так:

$ docker-compose down

или:

$ docker rm mysql-container

Дальше надо удалить хранилище (volume) с некорректно проинициализированной базой. Но в начале просмотрите список всех хранилищ:

$ docker volume ls

СЕРВЕР НЕВЕРНО ПРОИНИЦИАЛИЗИРОВАН

После удаляем:

$ docker volume rm имя_хранилища

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

Эта ошибка означает, что MySQL сервер запущен, но он отказывает вам в соединении. Это может произойти по нескольким причинам. Самых основных и часто встречающихся причин три: сервер перегружен, и у вас истекло время ожидания ответа, ваш клиент отправил слишком большой пакет или сервер был не до конца проинициализирован.

В этой небольшой статье мы рассмотрим более подробно, почему возникает ошибка 2006: MySQL server has gone away, а также — как её исправить.

Такую ошибку вы можете увидеть во время подключения к базе данных с помощью PHP, консольного клиента или, например, в PhpMyAdmin:

1. Истекло время ожидания

Как я уже писал выше, одной из причин может быть таймаут ожидания соединения. Возможно, сервер баз данных перегружен и не успевает обрабатывать все соединения. Вы можете подключиться к серверу с помощью консольного клиента, если вам это удастся, и попытаться выполнить какой-либо запрос, чтобы понять, действительно ли запросы выполняются слишком долго. Если это так, можно оптимизировать производительность MySQL с помощью скрипта MySQLTuner.

В большинстве случаев надо увеличить размер пула движка InnoDB с помощью параметра innodb_buffer_pool_size. Какое значение лучше поставить, можно узнать с помощью указанного выше скрипта. Например, 800 мегабайт:

sudo vi /etc/mysql/my.cnf

innodb_buffer_pool_size=800M

Есть и другой путь решения этой проблемы. Если такая скорость обработки запросов считается нормальной, можно увеличить время ожидания ответа от сервера. Для этого измените значение параметра wait_timeout. Это время в секундах, на протяжении которого надо ждать ответа от сервера. Например:

wait_timeout=600

После любых изменений не забудьте перезапустить MySQL сервер:

sudo systemctl restart mysql

или:

sudo systemctl restart mariadb

2. Слишком большой пакет

Если ваш клиент MySQL создаёт слишком большие пакеты с запросами к серверу, это тоже может стать причиной такой ошибки. Максимально доступный размер пакета можно увеличить с помощью параметра max_allowed_packet. Например:

sudo vi /etc/mysql/my.cnf

max_allowed_packet=128M

Обратите внимание, что если вы из своей программы отправляете большие пакеты, то, скорее всего, вы делаете что-то не так. Не надо генерировать запросы к MySQL с помощью циклов for. SQL — это отдельный язык программирования, который многое может сделать сам, без необходимости писать очень длинные запросы.

3. Сервер неверно проинициализирован

Такая проблема может возникать при разворачивании контейнера MySQL или MariaDB в Docker. Дело в том, что на первоначальную инициализацию контейнера нужно много времени: около нескольких минут. Если вы не дадите контейнеру завершить инициализацию, а остановите его и потом снова запустите, то база данных будет всегда возвращать такую ошибку.

Вам нужно полностью удалить данные контейнера с базой данных. Например, с помощью docker-compose:

docker-compose down

или вручную:

docker rm mysql-container

Здесь mysql-container — это имя контейнера с базой данных. А затем надо удалить хранилище (volume) с некорректно проинициализированной базой. Сначала посмотрите список всех хранилищ:

docker volume ls

Затем удалите нужное:

docker volume rm имя_хранилища

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

Выводы

В этой небольшой статье мы рассмотрели, что значит ошибка MySQL Server has gone away, а также как её исправить на сервере или в контейнере Docker. Вы знаете ещё другие причины и решения этой проблемы? Пишите в комментариях!

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Creative Commons License

Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .

Об авторе

Основатель и администратор сайта losst.ru, увлекаюсь открытым программным обеспечением и операционной системой Linux. В качестве основной ОС сейчас использую Ubuntu. Кроме Linux, интересуюсь всем, что связано с информационными технологиями и современной наукой.

Рассмотрим, как исправить ошибку MySQL server has gone away (error 2006), которая появляется при обращении к сервису MySQL.

Наиболее распространение причины ошибки MySQL server has gone away:

  • Слишком большой размер пакета в запросе к MySQL (по умолчанию максимальный размер — 16 Мб);
  • Закончилась свободная оперативная память (RAM) на сервере MySQL (проверить свободную память в Linux можно с помощью команды free –h)
  • Неактивное соединение между вашим приложением и MySQL (по умолчанию сессия разрывается через 8 часов).

ошибка mysql server has gone away (error 2006)

General error: 2006 MySQL server has gone away
Error Code: 2013. Lost connection to MySQL server during query
PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away

Чтобы увеличить таймаут для подключений к MySQL, нужно добавить следующие опции в конфигурационный файл mysqld.cnf:

sudo nano /etc/mysql/my.cnf

Найдите секцию [mysqld] и увеличьте таймаут до 24 часов:

wait_timeout = 86400
interactive_timeout = 86400

Если вы загружаете в MySQL большие файлы или BLOB объекты более 16 Мб, то MySQL с настройками по-умолчанию также может вернуть ошибку MySQL server has gone away. Нужно увеличить максимальный размер пакета в my.cnf.

Для этого в секции [mysqld] увеличьте значение параметра max_allowed_packet со стандартного 16M до 128MB:

max_allowed_packet = 128MB

После внесения изменений в файл mysqld.cnf нужно перезапустить сервис MySQL:

  • В CentOS/RHEL:sudo systemctl restart mysqld
  • В Ubuntu: sudo systemctl restart mysql.service

Если вы подключаетесь к MySQL из PHP, проверьте что значения таймаутов в php.ini больше, чем в MySQL

mysql.connect_timeout=86400
mysql.allow_persistent=1

Are you familiar with the ‘ERROR 2006 (HY000) at line XXX: MySQL server has gone away’ error message? If you have been working with MySQL and have encountered this error, it can be frustrating and even daunting, particularly if you’re unsure how to resolve it. This comprehensive guide will provide you with an understanding of what this error is, why it happens, and most importantly, how to resolve it.

What is ‘ERROR 2006 (HY000)?

Before we can begin to troubleshoot and resolve this error, we need to understand what it is. ‘ERROR 2006 (HY000) at line XXX: MySQL server has gone away’ is an error message that you might encounter when working with a MySQL database.

This error typically appears when you’re trying to perform an operation – such as a query or command – on a MySQL server that’s no longer available. The “XXX” in the error message will be replaced with the line number in your SQL code where the error occurred.

Why Does This Error Occur?

There could be several reasons why a MySQL server might go away during an operation. Here are a few common scenarios:

  1. Server Timeouts: If a connection has been idle for too long, the server may close the connection. The default timeout is usually 8 hours.
  2. Large Data Packet: If you’re trying to send a packet larger than ‘max_allowed_packet’, this error can occur. MySQL server can’t handle a packet larger than this set size.
  3. Server Shutdown: If the server was shut down or restarted, all existing connections would be lost.
  4. Lost Connection: This could be due to network issues between the client and the server.

Resolving ‘ERROR 2006 (HY000)

Now that we have a basic understanding of what this error is and why it might occur, let’s discuss how to resolve it.

1. Increase the Server Timeout

If the error is due to the server timing out, consider increasing the ‘wait_timeout’ and ‘interactive_timeout’ system variables. This can be done by adding or modifying these lines in your MySQL server’s my.cnf (Linux) or my.ini (Windows) file:

[mysqld]

wait_timeout = 28800

interactive_timeout = 28800

Remember, the timeout values are in seconds, and the above example sets the server timeout to 8 hours.

2. Increase the Maximum Allowed Packet Size

If the error is due to a packet being too large, you can increase the ‘max_allowed_packet’ system variable. This can also be done in the my.cnf or my.ini file:

[mysqld]

max_allowed_packet=64M

Even you can define the value at command line during backup or restore databases. For examples:

# To backup database

mysqldump —max_allowed_packet=64M -p my_database > my_database.sql

# To restore database

mysql —max_allowed_packet=64M -p my_database < my_database.sql

In the example above, the maximum allowed packet size is set to 64 megabytes. Be sure to set this value carefully, as setting it too high can use a lot of memory.

3. Ensure the Server is Running

If the server was shut down or restarted, simply making sure the server is running when you’re trying to use it might resolve the error. If the server is running on a different machine, make sure that machine is accessible.

4. Check Network Connectivity

If the error is due to a lost connection, try pinging the server from the client machine to verify that they can communicate. If there are any network issues, you’ll need to resolve them to get the MySQL server and client communicating again.

Conclusion

‘ERROR 2006 (HY000) at line XXX: MySQL server has gone away’ can be a frustrating issue to deal with, but understanding its causes and knowing how to resolve it can take a lot of the stress away. By adjusting server timeout values, increasing packet size, ensuring your server is running, and checking network connectivity, you’ll be well-equipped to handle this error. Remember, always backup your data before making any major changes to your system configuration to prevent any data loss.

Понравилась статья? Поделить с друзьями:
  • Mta ошибка сс23
  • Mta ошибка св09
  • Mta ошибка gta3 img
  • Mujuice ошибки слушать
  • Mta ошибка direct3d