Is there a mySQL connection time limit? - mysql

I'm using Net-SNMP on an Ubuntu 14.04 server to capture SNMP traps in snmptrapd, which I've set up (using "perl do '/path/to/traphandler.pl'" in the /etc/snmp/snmptrapd.conf) to call a Perl::DBI script to insert data into a mySQL database. Everything has been running fine since 16th March, then about 9am yesterday (6th April - Bank Holiday - typical) the database updates stopped, though the syslog shows that the traps were still coming in.
I can't see anything obvious in /var/log, so I'm wondering whether the database connection simply expired and closed. Does that happen? I stopped and restarted snmptrapd and it all started working again, which makes me think that was the cause. How would I check?

Yes it is 28800 seconds
connect_timeout=28800
wait_timeout=28800
interactive_timeout=28800
You can set the values in /etc/my.cnf
If you want to change it then you have to run this query:
SET GLOBAL interactive_timeout = 100; //Change it if you want
SET GLOBAL wait_timeout = 100;

If a service needs a database connection, the best is to check in the main loop or before each query if the connection is still available.
If the connection is no longer available or if it doesn't work anymore, you can close it properly and reconnect.
This way, the deamon continues to work even if the database server is temporarily unavailable. For instance, the service will continue to work even if the database server restarts.

Not exactly an answer to your question but you can handle lost db connections without altering a timeout or checking the connection before each query.
If you access MySQL databases with DBI you can set the flag mysql_auto_reconnect ( see DBD::mysql )
This attribute determines whether DBD::mysql will automatically reconnect to mysql if the connection be lost. This feature defaults to off; [..]
Setting mysql_auto_reconnect to on is not advised if 'lock tables' is used because if DBD::mysql reconnect to mysql all table locks will be lost.
Example:
my $dbh = DBI->connect(
$host,
$user,
$password,
{
mysql_auto_reconnect => 1
}
) or die("DB connect failed: : $DBI::errstr");

Related

HostGator mySQL connection time-outs after 10 seconds or so ---- how do I extend this?

for some reason when I open a connection the the Percona MySQL database on my HostGator website, after fetching the query, it will disconnect/ close the connection about 10 seconds later.
I typically wouldn't care, but HeidiSQL freezes up, preventing exporting or sorting the returned rows with it's UI unless I connect again.
Any thoughts on making the connection last longer? is it something I can do myself, or will it require a dedicated server or some upgrade? (I'm currently on a shared one). Thanks!
Sounds like it may be the "wait" timeout on the MySQL connection.
SHOW VARIABLES LIKE 'wait_timeout'
That's the amount of time (in seconds) that MySQL will leave the session (the database connection) open while it's idle, waiting for another statement to be issued. After this amount of time expires, MySQL can close the connection.
You should be able to change this for a session, to change the timeout to 5 minutes
SET wait_timeout = 300
Verify the setting with the SHOW VARIABLES statement again.
NOTE: This is per connection. It only affects the current session. Every new connection will inherit their own wait_timeout value from the global setting.
(This is only a guess. There's insufficient information in the question to make a precise diagnosis. It could be something other than MySQL server that's closing the database connection, e.g. it could be your connection pool settings (if you are using a connection pool).

Intermittent mySQL crash. phpmyadmin logs me out when I click on variables tab [duplicate]

I'm running a server at my office to process some files and report the results to a remote MySQL server.
The files processing takes some time and the process dies halfway through with the following error:
2006, MySQL server has gone away
I've heard about the MySQL setting, wait_timeout, but do I need to change that on the server at my office or the remote MySQL server?
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
Note: This can be set on your server as it's running.
Note: On Windows you may need to save your my.ini or my.cnf file with ANSI not UTF-8 encoding.
Use set global max_allowed_packet=104857600. This sets it to 100MB.
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.
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;
It may be easier to check if the connection exists and re-establish it if needed.
See PHP:mysqli_ping for info on that.
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
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.
In MAMP (non-pro version) I added
--max_allowed_packet=268435456
to ...\MAMP\bin\startMysql.sh
Credits and more details here
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 :)
This error is occur due to expire of wait_timeout .
Just go to mysql server check its wait_timeout :
mysql> SHOW VARIABLES LIKE 'wait_timeout'
mysql> set global wait_timeout = 600 # 10 minute or maximum wait time
out you need
http://sggoyal.blogspot.in/2015/01/2006-mysql-server-has-gone-away.html
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.
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.
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
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
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
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.
There is an easier way if you are using XAMPP.
Open the XAMPP control panel, and click on the config button in mysql section.
Now click on the my.ini and it will open in the editor. Update the max_allowed_packet to your required size.
Then restart the mysql service. Click on stop on the Mysql service click start again. Wait for a few minutes.
Then try to run your Mysql query again. Hope it will work.
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.
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:
Go to http://localhost/phpmyadmin
Go to SQL tab
Run SHOW VARIABLES and check the values, if it is small then run with big values
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;
For Vagrant Box, make sure you allocate enough memory to the box
config.vm.provider "virtualbox" do |vb|
vb.memory = "4096"
end
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
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.
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
I found the solution to "#2006 - MySQL server has gone away" this error.
Solution is just you have to check two files
config.inc.php
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:
config.inc.php
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.
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.
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}
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!
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.
For users using XAMPP, there are 2 max_allowed_packet parameters in C:\xampp\mysql\bin\my.ini.
This error happens basically for two reasons.
You have a too low RAM.
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.
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

MySQL error 2006: mysql server has gone away

I'm running a server at my office to process some files and report the results to a remote MySQL server.
The files processing takes some time and the process dies halfway through with the following error:
2006, MySQL server has gone away
I've heard about the MySQL setting, wait_timeout, but do I need to change that on the server at my office or the remote MySQL server?
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
Note: This can be set on your server as it's running.
Note: On Windows you may need to save your my.ini or my.cnf file with ANSI not UTF-8 encoding.
Use set global max_allowed_packet=104857600. This sets it to 100MB.
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.
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;
It may be easier to check if the connection exists and re-establish it if needed.
See PHP:mysqli_ping for info on that.
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
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.
In MAMP (non-pro version) I added
--max_allowed_packet=268435456
to ...\MAMP\bin\startMysql.sh
Credits and more details here
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 :)
This error is occur due to expire of wait_timeout .
Just go to mysql server check its wait_timeout :
mysql> SHOW VARIABLES LIKE 'wait_timeout'
mysql> set global wait_timeout = 600 # 10 minute or maximum wait time
out you need
http://sggoyal.blogspot.in/2015/01/2006-mysql-server-has-gone-away.html
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.
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.
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
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
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
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.
There is an easier way if you are using XAMPP.
Open the XAMPP control panel, and click on the config button in mysql section.
Now click on the my.ini and it will open in the editor. Update the max_allowed_packet to your required size.
Then restart the mysql service. Click on stop on the Mysql service click start again. Wait for a few minutes.
Then try to run your Mysql query again. Hope it will work.
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.
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:
Go to http://localhost/phpmyadmin
Go to SQL tab
Run SHOW VARIABLES and check the values, if it is small then run with big values
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;
For Vagrant Box, make sure you allocate enough memory to the box
config.vm.provider "virtualbox" do |vb|
vb.memory = "4096"
end
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
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.
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
I found the solution to "#2006 - MySQL server has gone away" this error.
Solution is just you have to check two files
config.inc.php
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:
config.inc.php
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.
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.
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}
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!
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.
For users using XAMPP, there are 2 max_allowed_packet parameters in C:\xampp\mysql\bin\my.ini.
This error happens basically for two reasons.
You have a too low RAM.
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.
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

mysql_ping() c api fails

connection to mysql is getting lost after 8 hours ( i.e afer wait_timeout varibale times out). i am trying to use mysql_ping() to reconnect to the server but ping gives me Mysql server gone away error. I am using sql version 5.1. so i am not using mysql_options() to enable the reconnect flag as mysql_real_connect() sets it to 0. I am explicitly setting the reconnect flag to 1 like mysql_Conn->reconnect =1; after calling mysql_real_connect().
But mysqlping doesn't work. The reconnection is not happening. Kindly advice.
Thanks in advance
Instead of trying to ping the connection back to life after it's dropped, far better to ping it periodically at about half the idle disconnect time (4 hours in your case) to keep it alive.
If the ping fails, drop the connection explicitly and reconnect.
Also, you might want to add something like this to your /etc/my.cnf:
[mysqld]
wait_timeout=400000
The timeout is in seconds, so this is about four and a half days, long enough to keep a connection alive over a long weekend while no one is using your system.

"MySQL server has gone away" with Ruby on Rails

After our Ruby on Rails application has run for a while, it starts throwing 500s with "MySQL server has gone away". Often this happens overnight. It's started doing this recently, with no obvious change in our server configuration.
Mysql::Error: MySQL server has gone away: SELECT * FROM `widgets`
Restarting the mongrels (not the MySQL server) fixes it.
How can we fix this?
Ruby on Rails 2.3 has a reconnect option for your database connection:
production:
# Your settings
reconnect: true
See:
Ruby on Rails 2.3 Release Notes, sub section 4.8 Reconnecting MySQL Connections.
MySQL auto-reconnect revisited
Good luck!
This is probably caused by the persistent connections to MySQL going away (time out is likely if it's happening over night) and Ruby on Rails is failing to restore the connection, which it should be doing by default:
In the file vendor/rails/actionpack/lib/action_controller/dispatcher.rb is the code:
if defined?(ActiveRecord)
before_dispatch { ActiveRecord::Base.verify_active_connections! }
to_prepare(:activerecord_instantiate_observers) {ActiveRecord::Base.instantiate_observers }
end
The method verify_active_connections! performs several actions, one of which is to recreate any expired connections.
The most likely cause of this error is that this is because a monkey patch has redefined the dispatcher to not call verify_active_connections!, or verify_active_connections! has been changed, etc.
Try ActiveRecord::Base.connection.verify! in Ruby on Rails 4. Verify pings the server and reconnects if it is not connected.
I had this problem when sending really large statements to MySQL. MySQL limits the size of statements and will close the connection if you go over the limit.
set global max_allowed_packet = 1048576; # 2^20 bytes (1 MB) was enough in my case
As the other contributors to this thread have said, it is most likely that MySQL server has closed the connection to your Ruby on Rails application because of inactivity. The default timeout is 28800 seconds, or 8 hours.
set-variable = wait_timeout=86400
Adding this line to your /etc/my.cnf will raise the timeout to 24 hours
http://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html#option_mysqld_wait_timeout.
Although the documentation doesn't indicate it, a value of 0 may disable the timeout completely, but you would need to experiment as this is just speculation.
There are however three other situations that I know of that can generate that error. The first is the MySQL server being restarted. This will obviously drop all the connections, but as the MySQL client is passive, and this won't be noticed till you do the next query.
The second condition is if someone kills your query from the MySQL command line, and this also drops the connection, because it could leave the client in an undefined state.
The last is if your MySQL server restarts itself due to a fatal internal error. That is, if you are doing a simple query against a table and instantly see 'MySQL has gone away', I'd take a close look at your server's logs to check for hardware error, or database corruption.
First, determine the max_connections in MySQL:
show variables like "max_connections";
You need to make sure that the number of connections you're making in your Ruby on Rails application is less than the maximum allowed number of connections. Note that extra connections can be coming from your cron jobs, delayed_job processes (each would have the same pool size in your database.yml), etc.
Monitor the SQL connections as you go through your application, run processes, etc. by doing the following in MySQL:
show status where variable_name = 'Threads_connected';
You might want to consider closing connections after a Thread finishes execution as database connections do not get closed automatically (I think this is less of an issue with Ruby on Rails 4 applications Reaper):
Thread.new do
begin
# Thread work here
ensure
begin
if (ActiveRecord::Base.connection && ActiveRecord::Base.connection.active?)
ActiveRecord::Base.connection.close
end
rescue
end
end
end
The connection to the MySQL server is probably timing out.
You should be able to increase the timeout in MySQL, but for a proper fix, have your code check that the database connection is still alive, and re-connect if it's not.
Using reconnect: true in the database.yml will cause the database connection to be re-established AFTER the ActiveRecord::StatementInvalid error is raised (As Dave Cheney mentioned).
Unfortunately adding a retry on the database operation seemed necessary to guard against the connection timeout:
begin
do_some_active_record_operation
rescue ActiveRecord::StatementInvalid => e
Rails.logger.debug("Got statement invalid #{e.message} ... trying again")
# Second attempt, now that db connection is re-established
do_some_active_record_operation
end
Do you monitor the number of open MySQL connections or threads? What is your mysql.ini settings for max_connections?
mysql> show status;
Look at Connections, Max_used_connections, Threads_connected, and Threads_created.
You may need to increase the limits in your MySQL configuration, or perhaps rails is not closing the connection properly*.
Note: I've only used Ruby on Rails briefly...
The MySQL documentation for server status is in http://dev.mysql.com/doc/refman/5.0/en/server-status-variables.html.
Something else to check is Unicorn config is correct. See before_fork and after_fork handling of ActiveRecord connection here: https://gist.github.com/nebiros/2776085#file-unicorn-rb
I had this problem in a Ruby on Rails 3 application, using the mysql2 gem. I copied out the offending query and tried running it in MySQL directly, and I got the same error, "MySQL server has gone away.".
The query in question was very, very large. A very large insert (+1 MB). The field I was trying to insert into was a TEXT column and their max size is 64 KB. Rather than throwing an errorm, the connection went away.
I increased the size of the field and got the same thing, so I'm still not sure what the exact issue was. The point is that it was in the database due to some strange query. Anyway!
While forking in Rails.
For anyone running into this while forking in Rails, try clearing the existing connections before forking and then establish a new connection for each fork, like this:
# Clear existing connections before forking to ensure they do not get inherited.
::ActiveRecord::Base.clear_all_connections!
fork do
# Establish a new connection for each fork.
::ActiveRecord::Base.establish_connection
# The rest of the code for each fork...
end
See this StackOverflow answer here: https://stackoverflow.com/a/8915353/293280