I got the Error Code: 2013. Lost connection to MySQL server during query error when I tried to add an index to a table using MySQL Workbench.
I noticed also that it appears whenever I run long query.
Is there away to increase the timeout value?
asked May 12, 2012 at 12:14
user836026user836026
10.2k13 gold badges72 silver badges125 bronze badges
New versions of MySQL WorkBench have an option to change specific timeouts.
For me it was under Edit → Preferences → SQL Editor → DBMS connection read time out (in seconds): 600
Changed the value to 6000.
Also unchecked limit rows as putting a limit in every time I want to search the whole data set gets tiresome.
Marko
20.3k13 gold badges48 silver badges64 bronze badges
answered Oct 8, 2012 at 22:49
15
If your query has blob data, this issue can be fixed by applying a my.ini
change as proposed in this answer:
[mysqld]
max_allowed_packet=16M
By default, this will be 1M (the allowed maximum value is 1024M). If the supplied value is not a multiple of 1024K, it will automatically be rounded to the nearest multiple of 1024K.
While the referenced thread is about the MySQL error 2006, setting the max_allowed_packet
from 1M to 16M did fix the 2013 error that showed up for me when running a long query.
For WAMP users: you’ll find the flag in the [wampmysqld]
section.
answered Jul 3, 2014 at 13:36
3
Start the DB server with the comandline option net_read_timeout
/ wait_timeout
and a suitable value (in seconds) — for example: --net_read_timeout=100
.
For reference see here and here.
answered May 12, 2012 at 12:17
YahiaYahia
69.1k9 gold badges113 silver badges143 bronze badges
2
SET @@local.net_read_timeout=360;
Warning: The following will not work when you are applying it in remote connection:
SET @@global.net_read_timeout=360;
Edit: 360 is the number of seconds
Vince V.
3,1192 gold badges29 silver badges45 bronze badges
answered Apr 20, 2015 at 3:58
user1313024user1313024
2594 silver badges3 bronze badges
2
Add the following into /etc/mysql/cnf file:
innodb_buffer_pool_size = 64M
example:
key_buffer = 16M
max_allowed_packet = 16M
thread_stack = 192K
thread_cache_size = 8
innodb_buffer_pool_size = 64M
Sam
1,1851 gold badge23 silver badges39 bronze badges
answered Apr 17, 2015 at 15:11
MysqlManMysqlMan
2172 silver badges2 bronze badges
2
In my case, setting the connection timeout interval to 6000 or something higher didn’t work.
I just did what the workbench says I can do.
The maximum amount of time the query can take to return data from the DBMS.Set 0 to skip the read timeout.
On Mac
Preferences -> SQL Editor -> Go to MySQL Session -> set connection read timeout interval to 0.
And it works 😄
answered Nov 26, 2019 at 3:55
Thet HtunThet Htun
4414 silver badges13 bronze badges
There are three likely causes for this error message
- Usually it indicates network connectivity trouble and you should check the condition of your network if this error occurs frequently
- Sometimes the “during query” form happens when millions of rows are being sent as part of one or more queries.
- More rarely, it can happen when the client is attempting the initial connection to the server
For more detail read >>
Cause 2 :
SET GLOBAL interactive_timeout=60;
from its default of 30 seconds to 60 seconds or longer
Cause 3 :
SET GLOBAL connect_timeout=60;
answered Dec 8, 2016 at 6:30
Nanhe KumarNanhe Kumar
15.1k5 gold badges78 silver badges70 bronze badges
1
You should set the ‘interactive_timeout’ and ‘wait_timeout’ properties in the mysql config file to the values you need.
answered May 12, 2012 at 12:19
Maksym PolshchaMaksym Polshcha
17.8k8 gold badges50 silver badges77 bronze badges
1
Just perform a MySQL upgrade that will re-build innoDB engine along with rebuilding of many tables required for proper functioning of MySQL such as performance_schema
, information_schema
, etc.
Issue the below command from your shell:
sudo mysql_upgrade -u root -p
Jamal
7587 gold badges22 silver badges31 bronze badges
answered May 19, 2014 at 20:16
Shoaib KhanShoaib Khan
89114 silver badges25 bronze badges
2
If you experience this problem during the restore of a big dump-file and can rule out the problem that it has anything to do with network (e.g. execution on localhost) than my solution could be helpful.
My mysqldump held at least one INSERT that was too big for mysql to compute. You can view this variable by typing show variables like "net_buffer_length";
inside your mysql-cli.
You have three possibilities:
- increase net_buffer_length inside mysql -> this would need a server restart
- create dump with
--skip-extended-insert
, per insert one line is used -> although these dumps are much nicer to read this is not suitable for big dumps > 1GB because it tends to be very slow - create dump with extended inserts (which is the default) but limit the net-buffer_length e.g. with
--net-buffer_length NR_OF_BYTES
where NR_OF_BYTES is smaller than the server’s net_buffer_length -> I think this is the best solution, although slower no server restart is needed.
I used following mysqldump command:
mysqldump --skip-comments --set-charset --default-character-set=utf8 --single-transaction --net-buffer_length 4096 DBX > dumpfile
answered Jan 8, 2016 at 11:07
Matt VMatt V
931 silver badge5 bronze badges
On the basis of what I have understood this error was caused due to read timeout
and max allowed packet
default is 4M. if your query file more than 4Mb then you get an error. this worked for me
- change the read timeout. For changing go to
Workbench Edit → Preferences → SQL Editor
2. change the max_allowed_packet manually by editing the file my.ini
. for editing go to "C:ProgramDataMySQLMySQL Server 8.0my.ini"
. The folder ProgramData
folder is hidden so if you did not see then select show hidden file in view settings. set the max_allowed_packet = 16M
in my.ini
file.
3. Restart MySQL. for restarting go to win+ R -> services.msc
and restart MySQL.
answered Mar 24, 2022 at 6:15
AvinashAvinash
1412 silver badges4 bronze badges
0
I know its old but on mac
1. Control-click your connection and choose Connection Properties.
2. Under Advanced tab, set the Socket Timeout (sec) to a larger value.
answered Mar 27, 2015 at 6:53
Aamir MahmoodAamir Mahmood
2,6843 gold badges27 silver badges47 bronze badges
1
Sometimes your SQL-Server gets into deadlocks, I’ve been in to this problem like 100 times. You can either restart your computer/laptop to restart server (easy way) OR you can go to task-manager>services>YOUR-SERVER-NAME(for me , it was MySQL785 something like this). And right-click > restart.
Try executing query again.
answered Feb 10, 2021 at 13:28
Try please to uncheck limit rows in in Edit → Preferences →SQL Queries
because You should set the ‘interactive_timeout’ and ‘wait_timeout’ properties in the mysql config file to the values you need.
answered Jul 24, 2014 at 9:59
user2586714user2586714
1491 gold badge1 silver badge7 bronze badges
Change «read time out» time in Edit->Preferences->SQL editor->MySQL session
answered Apr 21, 2016 at 9:25
I got the same issue when loading a .csv file.
Converted the file to .sql.
Using below command I manage to work around this issue.
mysql -u <user> -p -D <DB name> < file.sql
Hope this would help.
answered Sep 8, 2016 at 6:19
VinRockaVinRocka
3074 silver badges15 bronze badges
Go to Workbench Edit → Preferences → SQL Editor → DBMS connections read time out : Up to 3000.
The error no longer occurred.
answered Sep 1, 2018 at 2:50
I faced this same issue. I believe it happens when you have foreign keys to larger tables (which takes time).
I tried to run the create table statement again without the foreign key declarations and found it worked.
Then after creating the table, I added the foreign key constrains using ALTER TABLE query.
Hope this will help someone.
answered Dec 23, 2016 at 7:22
Nimeshka SrimalNimeshka Srimal
7,5945 gold badges44 silver badges56 bronze badges
This happened to me because my innodb_buffer_pool_size was set to be larger than the RAM size available on the server. Things were getting interrupted because of this and it issues this error. The fix is to update my.cnf with the correct setting for innodb_buffer_pool_size.
answered Feb 26, 2017 at 15:35
Go to:
Edit -> Preferences -> SQL Editor
In there you can see three fields in the «MySQL Session» group, where you can now set the new connection intervals (in seconds).
answered May 5, 2017 at 13:23
Turns out our firewall rule was blocking my connection to MYSQL. After the firewall policy is lifted to allow the connection i was able to import the schema successfully.
answered May 11, 2017 at 15:38
I had the same problem — but for me the solution was a DB user with too strict permissions.
I had to allow the Execute
ability on the mysql
table. After allowing that I had no dropping connections anymore
answered Aug 31, 2017 at 17:35
naabsternaabster
1,47612 silver badges14 bronze badges
Check if the indexes are in place first.
SELECT *
FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA = '<schema>'
answered Sep 22, 2017 at 3:58
Gayan DasanayakeGayan Dasanayake
1,8932 gold badges17 silver badges21 bronze badges
I ran into this while running a stored proc- which was creating lots of rows into a table in the database.
I could see the error come right after the time crossed the 30 sec boundary.
I tried all the suggestions in the other answers. I am sure some of it helped , however- what really made it work for me was switching to SequelPro from Workbench.
I am guessing it was some client side connection that I could not spot in Workbench.
Maybe this will help someone else as well ?
answered Dec 19, 2017 at 21:19
RN.RN.
9974 gold badges14 silver badges30 bronze badges
If you are using SQL Work Bench, you can try using Indexing, by adding an index to your tables, to add an index, click on the wrench(spanner) symbol on the table, it should open up the setup for the table, below, click on the index view, type an index name and set the type to index, In the index columns, select the primary column in your table.
Do the same step for other primary keys on other tables.
answered Jun 25, 2018 at 8:21
Matthew EMatthew E
5855 silver badges6 bronze badges
There seems to be an answer missing here for those using SSH to connect to their MySQL database. You need to check two places not 1 as suggested by other answers:
Workbench Edit → Preferences → SQL Editor → DBMS
Workbench Edit → Preferences → SSH → Timeouts
My default SSH Timeouts were set very low and causing some (but apparently not all) of my timeout issues. After, don’t forget to restart MySQL Workbench!
Last, it may be worth contacting your DB Admin and asking them to increase wait_timeout & interactive_timeout properties in mysql itself via my.conf + mysql restart or doing a global set if restarting mysql is not an option.
Hope this helps!
answered May 6, 2019 at 17:36
Three things to be followed and make sure:
- Whether multiple queries show lost connection?
- how you use set query in MySQL?
- how delete + update query simultaneously?
Answers:
- Always try to remove definer as MySQL creates its own definer and if multiple tables involved for updation try to make a single query as sometimes multiple query shows lost connection
- Always SET value at the top but after DELETE if its condition doesn’t involve SET value.
- Use DELETE FIRST THEN UPDATE IF BOTH OF THEM OPERATIONS ARE PERFORMED ON DIFFERENT TABLES
RalfFriedl
1,1363 gold badges10 silver badges12 bronze badges
answered Sep 22, 2019 at 16:10
I had this error message due to a problem after of upgrade Mysql. The error appeared immediately after I tried to do any query
Check mysql error log files in path /var/log/mysql
(linux)
In my case reassigning Mysql owner to the Mysql system folder worked for me
chown -R mysql:mysql /var/lib/mysql
answered Jan 23, 2021 at 19:29
franciscorodefranciscorode
5651 gold badge7 silver badges15 bronze badges
Establish connection first
mysql --host=host.com --port=3306 -u username -p
then select your db use dbname
then source dumb source C:dumpfile.sql
.
After it’s done q
answered Oct 29, 2021 at 5:32
If you spend time running lots of MySQL queries, you might come across the Error Code: 2013. Lost connection to MySQL server during query
. This article offers some suggestions on how to avoid or fix the problem.
Why this happens
This error appears when the connection between your MySQL client and database server times out. Essentially, it took too long for the query to return data so the connection gets dropped.
Most of my work involves content migrations. These projects usually involve running complex MySQL queries that take a long time to complete. I’ve found the WordPress wp_postmeta table especially troublesome because a site with tens of thousands of posts can easily have several hundred thousand postmeta entries. Joins of large datasets from these types of tables can be especially intensive.
Avoid the problem by refining your queries
In many cases, you can avoid the problem entirely by refining your SQL queries. For example, instead of joining all the contents of two very large tables, try filtering out the records you don’t need. Where possible, try reducing the number of joins in a single query. This should have the added benefit of making your query easier to read. For my purposes, I’ve found that denormalizing content into working tables can improve the read performance. This avoids time-outs.
Re-writing the queries isn’t always option so you can try the following server-side and client-side workarounds.
Server-side solution
If you’re an administrator for your MySQL server, try changing some values. The MySQL documentation suggests increasing the net_read_timeout
or connect_timeout
values on the server.
Client-side solution
You can increase your MySQL client’s timeout values if you don’t have administrator access to the MySQL server.
MySQL Workbench
You can edit the SQL Editor preferences in MySQL Workbench:
- In the application menu, select Edit > Preferences > SQL Editor.
- Look for the MySQL Session section and increase the DBMS connection read time out value.
- Save the settings, quite MySQL Workbench and reopen the connection.
Navicat
How to edit Navicat preferences:
- Control-click on a connection item and select Connection Properties > Edit Connection.
- Select the Advanced tab and increase the Socket Timeout value.
Command line
On the command line, use the connect_timeout
variable.
Python script
If you’re running a query from a Python script, use the connection argument:
con.query('SET GLOBAL connect_timeout=6000')
Is your database restore stuck with MySQL Error 2013 (hy000)?
Often queries or modifications in large databases result in MySQL errors due to server timeout limits.
At Bobcares, we often get requests to fix MySQL errors, as a part of our Server Management Services.
Today, let’s see how our Support Engineers fix MySQL Error 2013 (hy000) for our customers.
Why this MySQL Error 2013 (hy000) happens?
While dealing with MySQL, we may encounter some errors. Today, we are going to discuss one such error.
This MySQL 2013 error occurs during a restore of databases via mysqldump, in MySQL replication, etc.
This error appears when the connection between MySQL client and database server times out.
In general, this happens in databases with large tables. As a result, it takes too much time for the query to return data and the connection drops with an error.
Other reasons for the error include a large number of aborted connections, insufficient server memory, server restrictions, etc.
How do we fix MySQL Error 2013 (hy000)?
The fix for MySQL Error 2013 (hy000) depends a lot on the triggering reason. Let’s now see how our MySQL Engineers help customers solve it.
1. Changing MySQL limits
Recently, one of our customers approached us saying that he is getting an error like the one shown below while he is trying to connect with MySQL server.
So, our Engineers checked in detail and found that the connect_timeout value was set to only a few seconds. So, we increased it to 10 in the MySQL configuration file. For that, we followed the steps below:
Firstly, we opened the MySQL configuration file at /etc/mysql/my.cnf
Then, we searched for connect_timeout and set it as:
connect_timeout=10
Then we tried connecting with MySQL server and we were successful.
Additionally, it requires the proper setting of the variable max_allowed_packet in the MySQL configuration file too. While trying to restore the dump file in GB sizes, we increase the value to a higher one.
2. Disable Access restrictions
Similarly, this error also appears when the host has access restrictions. In such cases, we fix this by adding the client’s IP in /etc/hosts.allow or allow it in the server firewall.
Also, the error can happen due to the unavailability of the server. Recently, in a similar instance, the problem was not related to MySQL server or MySQL settings. We did a deep dig and found that high network traffic is causing the problem.
When we checked we found that a weird process running by the Apache user. So, we killed that and this fixed the error.
3. Increasing Server Memory
Last and not least, MySQL memory allocation also becomes a key factor for the error. Here, the server logs will have related entries showing the insufficient memory limit.
Therefore, our Dedicated Engineers reduce the innodb_buffer_pool size. This reduces the memory allocation on the server and fixes the error.
[Need assistance with MySQL errors – We can help you fix it]
Conclusion
In short, we discussed in detail on the causes for MySQL Error 2013 (hy000) and saw how our Support Engineers fix this error for our customers.
PREVENT YOUR SERVER FROM CRASHING!
Never again lose customers to poor server speed! Let us help you.
Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.
GET STARTED
var google_conversion_label = «owonCMyG5nEQ0aD71QM»;
The misstep depicted in the title of this article is entirely outstanding. A couple of attempts on handling the issue exist in various articles on the web. However, in error 2013 you lost connection to MySQL server during a query, concerning this article, there is a specific condition that is exceptionally novel so in the end, it causes the error to occur. The error occurs with the specific error message. That error message is in the going with yield message:
- root@hostname ~# mysql – uroot – p – h 127.0.0.1 – P 4406
- Enter secret key:
- Error 2013 (HY000): Lost relationship with MySQL server at ‘examining initial correspondence bundle’, system error: 0
- root@hostname ~#
The above error message is a result of partner with a MySQL Database Server. It is a standard MySQL Database Server running on a machine. However, the real connection is a substitute one. The connection exists using Worker holder running collaboration. Coming up next is the reliable running course of that Worker holder:
- root@hostname ~# netstat – tulpn | grep 4406
- tcp6 0:4406: * LISTEN 31814/worker-go-between
- root@hostname ~#
There are at this point lots of articles analyze about this mix-up. For a model in this association in the stack overflow or this association and one more in this association, besides in this association. The general issue is truly something almost identical. There is something misguided in the running arrangement of the regular MySQL Database Server.
Why this happens
This misstep appears when the relationship between your MySQL client and database server times out. Essentially, it took unreasonably long for the request to return data so the connection gets dropped.
By far most of my work incorporates content migrations. These activities for the most part incorporate running complex MySQL requests that burn through a huge lump of the day to wrap up. I’ve found the WordPress wp_postmeta table especially hazardous considering the way that a site with countless posts can without a very remarkable stretch have two or three hundred thousand post meta sections. Joins of enormous datasets from such tables can be especially genuine.
Avoid the issue by sanitizing your requests
Generally speaking, you can avoid the issue absolutely by refining your SQL questions. For example, instead of joining all of the substance of two especially immense tables, have a go at filtering through the records you needn’t waste time with. Where possible, have a go at reducing the amount of partakes in a singular inquiry. This should have the extra benefit of simplifying your inquiry to examine. For my inspirations, I’ve found that denormalizing content into working tables can deal with the read execution. This avoids breaks.
Re-making the inquiries isn’t, by and large, another option so you can effort the going with server-side and client-side workarounds.
A server-side course of action
If you’re ahead for your MySQL server, make a pass at changing a couple of characteristics. The MySQL documentation proposes extending the net_read_timeout or connect timeou
t values on the server.
The client-side course of action
You can extend your MySQL client’s sever regards on the possibility that you don’t have exclusive induction to the MySQL server.
MySQL Worktable
You can adjust the SQL Editor tendencies in MySQL Work Table:
- In the application menu, select Edit > Preferences > SQL Editor.
- Quest for the MySQL Session portion and augmentation the DBMS connection read break regard.
- Save the settings, very MySQL Work Table, and return the connection.
Step for handling the issue
There are a couple of stages for handling the issue above. There are two segments for handling the issue. The underlying portion is for perceiving the principal driver of the issue. Later on, the ensuing part is the genuine plan taken for tending to the fundamental driver of that issue. Thusly, going with the region which is the underlying portion will focus on power to search for the justification behind the issue.
Glancing through the justification behind the issue
Because of this article, coming up next is the means for settling the mix-up
- Check whether the MySQL Database Server measure is truly running. Effect it as follows using any request plan open in the working for truly taking a gander at a running connection. Concerning this article, it is ‘systemctl status MySQL. Thusly, coming up next is a model for the execution of the request plan:
- root@hostname ~# systemctl status MySQL
- service – MySQL Community Server
- Stacked: stacked (/lib/systemd/structure/mysql.service; horrible; vendor preset: engaged)
- Dynamic: dynamic (running) since Mon 2019-09-16 13:16:12; 40s back
- Cycle: 14867 ExecStart=/usr/sbin/mysqld – demonize – pid-file=/run/mysqld/mysqld. Pid (code=exited, status=0/SUCCESS)
- Connection: 14804 ExecStartPre=/usr/share/mysql/mysql-systemd-start pre (code=exited, status=0/SUCCESS)
- Guideline PID: 14869 (mysqld)
- Tasks: 31 (limit: 4915)
- Group:/system. Slice/mysql.service
- └─14869/usr/sbin/mysqld – daemonize – pid-file=/run/mysqld/mysqld. Pid
- root@hostname ~#
- Preceding partner with MySQL Database Server using a substitute port focusing on any moving toward requesting where it is a worker compartment measure dealing with, basically test the regular connection. By the day’s end, the partner using the normal port tuning in the machine for any moving toward a relationship with MySQL Database Server. Normally, it exists in port ‘3306’. Do it as follow:
- root@hostname ~# mysql – uroot
- Goof 2002 (HY000): Can’t interface with neighborhood MySQL server through connection ‘/var/run/mysqld/mysqld. Sock’ (2)
- root@hostname ~#
The above screw-up message is where the genuine root issue is. Check for the genuine report which is tending to the connection record for MySQL daemon measure as follows:
- root@hostname ~# disc/var/run/mysqld/
- root@hostname ~# ls
- Pid MySQL. sock MySQL. sock. Lock
- root@hostname ~#
As shown by the above yield, the report doesn’t exist. That is the explanation the relationship with MySQL Database Server is continually failed. Even though the connection cooperation is done through the default port of ‘3306’.
- The effort to restart the cooperation and trust that it will handle the issue.
- root@hostname ~# systemctl stop MySQL
- root@hostname ~# systemctl start MySQL
- root@hostname ~# mysql – uroot
- Slip-up 2002 (HY000): Can’t interface with neighborhood MySQL server through connection ‘/var/run/mysqld/mysqld. Sock’ (2)
- root@hostname ~#
- Unfortunately, the above cycle moreover wraps up in disappointment. Progress forward the movement for handling the issue, just check the MySQL Database arrangement record. In the wake of really investigating the report course of action, it doesn’t fit in any way shape, or form. Eventually, going through hours for changing the arrangement records, nothing happens.
For the reason happens above, check the right game plan before to see which MySQL Database Server arrangement is used by the running MySQL Database Server.
How might we fix MySQL Error 2013 (hy000)?
The fix for MySQL Error 2013 (hy000) depends a ton upon the setting off reason. We should now see how our MySQL Engineers help customers with settling it.
1. Changing MySQL limits
Lately, one of our customers pushed toward us saying that he is getting a mix-up as the one showed underneath while he is efforting to interface with the MySQL server.
Along these lines, our Engineers checked thoroughly and found that the connect timeout regard was set to two or three minutes. Thusly, we extended it to 10 in the MySQL arrangement record. For that, we followed the means underneath:
First thing, we opened the MySQL plan archive at, etc/MySQL/my.cnf
Then, we searched for connect timeout and set it as:
connect timeout=10
Then, we had a go at partner with MySQL server and we were viable.
Additionally, it requires the genuine setting of the variable max_allowed_packet in the MySQL arrangement record also. While efforting to restore the landfill record in GB sizes, we increase the value to a higher one.
2. Disabled person Access limits
This slip-up in like manner appears when the host approaches impediments. In such cases, we fix this by adding the client’s IP in, etc/hosts. Allow or license it in the server firewall.
Similarly, the error can happen as a result of the detachment of the server. Lately, in a similar case, the issue was not related to MySQL server or MySQL settings. We did a significant tunnel and found that high association traffic is causing the issue.
Exactly when we checked we found that an unconventional communication running by the Apache customer. Thusly, we killed that, and this good misstep.
3. Growing Server Memory
Last and not least, MySQL memory apportioning furthermore transforms into a basic factor for the slip-up. Here, the server logs will have related segments showing the lacking memory limit.
Subsequently, our Dedicated Engineers decline the innodb_buffer_pool size. This reduces the memory segment on the server and fixes the slip-up.
Checking the MySQL Database Server configuration used by the running MySQL Database Server
In the past fragment or part, there is a need to search for the real plan report used by the running MySQL Database Server. It is essential to guarantee that the plan record used is the right one. Thusly, every change can invite the right impact on dealing with the mix-up issue. Coming up next is the movement for searching for it:
- Truly check out the once-over of the assistance first by suggesting the running framework. In the past part, the running framework is the ‘MySQL one. Execute the going with request guide to list the open running cycle:
systemctl list-unit-reports | grep MySQL
The yield of the above request plan for a model is in the going with one:
- user hostname: ~$ systemctl list-unit-archives | grep MySQL
- service horrendous
- Service horrendous
- user hostname: ~$
- Then, at that point, truly investigate the substance of the help by executing the going with the request. Pick the right help, in this particular circumstance, it is ‘MySQL. service’:
- user hostname: ~$ systemctl cat myself. service
- #/lib/system/structure/Mysql.service
- # MySQL systemd organization record
- [Unit]
- Description=MySQL Community Server
- After=network. Target
- [Install]
- Wanted by=multi-user. Target
- [Service]
- Type=forking
- User=mysql
- Group=mysql
- PIDFile=/run/mysqld/mysqld. Pid
- PermissionsStartOnly=true
- ExecStartPre=/usr/share/mysql/mysql-systemd-start pre
- ExecStart=/usr/sbin/mysqld – daemonize – pid-file=/run/mysqld/mysqld. Pid
- Timeouts=600
- Restart=on-dissatisfaction
- Runtime Directory=mysqld
- RuntimeDirectoryMode=755
- LimitNOFILE=5000
- user hostname: ~$
- The record obligated for starting the help is in the archive ‘/usr/share/MySQL/MySQL-systems-start’ according to the yield message above. Coming up next is the substance of that record which is only fundamental for it:
- if [! – r, etc/MySQL/my.cnf]; then,
- resonation “MySQL arrangement not found at, etc/MySQL/my.in. Assuming no one minds, make one.”
- leave 1
- fi
- …..
- Resulting in truly taking a gander at the substance of the report ‘/, etc/MySQL/my.on, obviously, it isn’t the right record. Accordingly, to be more exact, there are other ways to deal with find the planned archive used by the running MySQL Database Server. The reference or the information exists in this association. Hence, according to the information in that association, basically perform the going with request guide to get the right one. It is forgetting the cycle ID and the right MySQL Database Server running collaboration:
- root@hostname ~# netstat – tulpn | grep 3306
- tcp6 0:3306: * LISTEN 21192/mysqld
- root@hostname ~# ps aux | grep 21192
- root@hostname ~# ps aux | grep 21192
- mysql 21192 0.2 0.1 3031128 22664? Sl Sep16 1:39/usr/sbin/mysqld – daemonize – pid-file=/run/mysqld/mysqld. Pid
- root 25442 0.0 23960 1068 pts/20 S+ 01:41 0:00 grep 21192
- root@hostname ~#
- Ensuing to getting the right running cycle, do the going with the request of ‘trace file_name_process’:
- root@hostname ~# album/usr/bin/
- root@hostname ~# strace. /mysqld
- Coming up next is fundamental for the yield of the request:
- detail, etc/my.cnf”, 0x7fff2e917880) = – 1 ENOENT (No such archive or vault)
- detail, etc/mysql/my.cnf”, {st_mode=S_IFREG|0644, st_size=839, …}) = 0
- openat (AT_FDCWD, “/, etc/mysql/my.cnf”, O_RDONLY) = 3
- fstat (3, {st_mode=S_IFREG|0644, st_size=839, …}) = 0
- brk(0x35f6000) = 0x35f6000
- read (3, “#n# The MySQL data base server co”…, 4096) = 839
- openat (AT_FDCWD, “/, etc/mysql/conf. d/”, O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_DIRECTORY) = 4
- fstat (4, {st_mode=S_IFDIR|0755, st_size=4096, …}) = 0
- get dents (4, /* 4 entries */, 32768) = 120
- get dents (4, /* 0 entries */, 32768) = 0
- close (4) = 0
- detail, etc/mysql/conf.d/mysql.cnf”, {st_mode=S_IFREG|0644, st_size=629, …}) = 0
- openat (AT_FDCWD, “/, etc/mysql/conf.d/mysql.cnf”, O_RDONLY) = 4
- fstat (4, {st_mode=S_IFREG|0644, st_size=629, …}) = 0
- read (4, “[mysqld]nn# Connection and Three”…, 4096) = 629
- read (4, “”, 4096) = 0
- close (4) = 0
- detail, etc/mysql/conf.d/mysqldump.cnf”, {st_mode=S_IFREG|0644, st_size=55, …}) = 0
- openat (AT_FDCWD, “/, etc/mysql/conf.d/mysqldump.cnf”, O_RDONLY) = 4
- fstat (4, {st_mode=S_IFREG|0644, st_size=55, …}) = 0
- read (4, “[MySQL dump] nquicknquote-namesnma”…, 4096) = 55
- read (4, “”, 4096) = 0
- close (4) = 0
- read (3, “”, 4096) = 0
- close (3) = 0
- detail (“/root/.my. cnf”, 0x7fff2e917880) = – 1 ENOENT (No such record or list)
The right one is finally in ‘/, etc/MySQL/conf.d/mysql.cf. Resulting in truly investigating the substance of the record, it is an empty archive. This is its essential driver. There has been some update and inverse present type of the MySQL Database Server, it making some disaster area the MySQL Database Server. The plan is essentially to fill that empty plan record with the right arrangement. The reference for the right arrangement of MySQL Database Server exists in this association. Restart the MySQL Server again, the above error issue will be tended to.
I’m trying to load mysqldump
and I keep getting following error:
ERROR 2013 (HY000) at line X: Lost connection to MySQL server during
query
/etc/my.cnf
:
[mysqld]
max_allowed_packet = 16M
net_read_timeout = 30
net_write_timeout = 60
...
[mysqldump]
max_allowed_packet = 16M
I tried to increase these values, but I keep getting that error no matter what( What else can I do to overcome this error?
asked Jan 1, 2016 at 0:12
alexusalexus
5954 gold badges13 silver badges28 bronze badges
2
If all the other solutions here fail — check your syslog (/var/log/syslog or similar) to see if your server is running out of memory during the query.
Had this issue when innodb_buffer_pool_size was set too close to physical memory without a swapfile configured. MySQL recommends for a database specific server setting innodb_buffer_pool_size at a max of around 80% of physical memory, I had it set to around 90%, the kernel was killing the mysql process. Moved innodb_buffer_pool_size back down to around 80% and that fixed the issue.
answered Jan 5, 2017 at 18:48
A_funsA_funs
2092 silver badges4 bronze badges
2
The error code ERROR 2013 (HY000)
related with aborted connection. You can run the following command to verify this.
mysql> SHOW GLOBAL STATUS LIKE 'Aborted_connects';
If the counter getting increased one by each attempt to connect, then it is an issue with connection.
One way to solve this issue, you can increase the connection timeout value in your configuration file. You can do that by using the following command.
mysql> SET GLOBAL connect_timeout = 10;
I hope this will help you. Thank you.
answered Jan 1, 2016 at 13:05
Rathish Kumar BRathish Kumar B
2,1345 gold badges20 silver badges34 bronze badges
2
@A_funs was right, inspecting the system log yields this:
Aug 14 08:04:15 centos-php55 kernel: Killed process 8597 (mysqld) total-vm:7395680kB, anon-rss:3351108kB, file-rss:0kB, shmem-rss:0kB
Aug 14 08:04:15 centos-php55 mysqld_safe[7848]: /usr/bin/mysqld_safe: line 200: 8597 Killed LD_PRELOAD=/usr/lib64/libjemalloc.so.1 nohup /usr/sbin/mysqld --basedir=/usr --datadir=/var/lib/mysql --plugin-dir=/usr/lib64/mysql/plugin --user=mysql --log-error=/var/lib/mysql/mysql-error.log --open-files-limit=1024000 --pid-file=/var/lib/mysql/mysql.pid --socket=/var/lib/mysql/mysql.sock < /dev/null > /dev/null 2>&1
So it might very well be possible you’re (like me) running out of memory on the machine. My problem was that MySQL was using too much memory so the scheduler was killing the process. Actually lowering innodb_buffer_pool_size
fixed the issue.
answered Aug 14, 2018 at 8:09
adioe3adioe3
1353 bronze badges
4
What command are you using to load mysqldump?
Is this a production server?
Size of the dump?
Format of the dump (.gz or .sql)?
Check if the error caused due to restart,if yes
1) check mysql memory allocation
2) try to reduce memory allocation by reducing innodb_buffer_pool size
This will help to reduce swap usage.
answered Apr 11, 2017 at 4:46
1
Содержание
- Код ошибки: 2013. Потерянное соединение с сервером MySQL во время запроса
- ОТВЕТЫ
- Ответ 1
- Ответ 2
- Ответ 3
- Ответ 4
- Ответ 5
- Ответ 6
- Ответ 7
- Ответ 8
- Ответ 9
- Ответ 10
- Ответ 11
- Ответ 12
- Ответ 13
- Ответ 14
- Ответ 15
- Ответ 16
- Ответ 17
- Ответ 18
- Ответ 19
- Ответ 20
- Ответ 21
- Ответ 22
- Ответ 23
- Ответ 24
- Ответ 25
- Ответ 26
- Ответ 27
- Ответ 28
- Код ошибки: 2013. Потерянное соединение с сервером MySQL во время запроса
- ОТВЕТЫ
- Ответ 1
- Ответ 2
- Ответ 3
- Ответ 4
- Ответ 5
- Ответ 6
- Ответ 7
- Ответ 8
- Ответ 9
- Ответ 10
- Ответ 11
- Ответ 12
- Ответ 13
- Ответ 14
- Ответ 15
- Ответ 16
- Ответ 17
- Ответ 18
- Ответ 19
- Ответ 20
- Ответ 21
- Ответ 22
- Ответ 23
- Ответ 24
- Ответ 25
- Ответ 26
- Ответ 27
- Ответ 28
Код ошибки: 2013. Потерянное соединение с сервером MySQL во время запроса
Я получил код Код ошибки: 2013. Потерянное подключение к MySQL-серверу во время запроса при попытке добавить индекс в таблицу с помощью MySQL Workbench. Я также заметил, что он появляется, когда я запускаю длинный запрос.
Есть ли возможность увеличить значение таймаута?
ОТВЕТЫ
Ответ 1
Новые версии MySQL WorkBench имеют возможность изменять определенные тайм-ауты.
Для меня это было в разделе Редактировать → Настройки → Редактор SQL → Время ожидания подключения к СУБД (в секундах): 600
Изменено значение до 6000.
Также не проверенные предельные строки, как ограничение лимита в каждый раз, когда я хочу искать весь набор данных, становятся утомительными.
Ответ 2
Запустите сервер БД с помощью опции comandline net_read_timeout / wait_timeout и подходящего значения (в секундах) — например: —net_read_timeout=100 .
Для справки см. здесь и здесь.
Ответ 3
Если у вашего запроса есть данные blob, эту проблему можно устранить, применив my.ini change как предлагается в этом ответе:
По умолчанию это будет 1M (допустимое максимальное значение равно 1024M). Если заданное значение не кратно 1024 КБ, оно будет автоматически округлено до ближайшего кратного 1024 КБ.
В то время как связанный поток относится к ошибке MySQL 2006 года, установка max_allowed_packet с 1M до 16M исправила ошибку 2013, которая появилась для меня при запуске длинного запроса.
Для пользователей WAMP: вы найдете флаг в разделе [wampmysqld] .
Ответ 4
Добавьте в файл /etc/mysql/cnf следующее:
Ответ 5
Предупреждение. Следующие действия не будут работать, если вы применяете его в удаленном соединении:
Ответ 6
Для этого сообщения об ошибке есть три причины
- Обычно это указывает на проблемы с подключением к сети, и вы должны проверить состояние своей сети, если эта ошибка возникает часто
- Иногда форма «во время запроса» возникает, когда миллионы строк отправляются как часть одного или нескольких запросов.
- Реже это может произойти, когда клиент пытается выполнить первоначальное подключение к серверу
от значения по умолчанию от 30 секунд до 60 секунд или дольше
Ответ 7
Вы должны установить свойства «interactive_timeout» и «wait_timeout» в файле конфигурации mysql для значений, которые вам нужны.
Ответ 8
Спасибо, это сработало. Но с обновлениями mysqldb настройка стала:
Ответ 9
Просто выполните обновление MySQL, которое будет перестроить механизм innoDB вместе с перестройкой многих таблиц, необходимых для правильной работы MySQL, таких как performance_schema , information_schema и т.д.
Выпустите следующую команду из своей оболочки:
Ответ 10
Я знаю его старый, но на mac
Ответ 11
Измените время ожидания чтения в Edit- > Preferences- > SQL-редакторе- > сеансе MySQL
Ответ 12
Попробуйте снять флажки с ограничениями строк в разделе «Редактировать» → «Настройки» → «Запросы SQL»
потому что вы должны установить свойства «interactive_timeout» и «wait_timeout» в конфигурационном файле mysql для значений, которые вам нужны.
Ответ 13
Если вы столкнулись с этой проблемой во время восстановления большого файла дампа и можете исключить проблему, связанную с сетью (например, выполнение на локальном хосте), может оказаться полезным мое решение.
Мой mysqldump провел хотя бы один INSERT, который был слишком большим для вычисления mysql. Вы можете просмотреть эту переменную, набрав show variables like «net_buffer_length»; внутри вашего mysql-cli. У вас есть три возможности:
- увеличить net_buffer_length внутри mysql → для этого потребуется перезагрузка сервера
- создать дамп с —skip-extended-insert , для каждой вставки используется одна строка → хотя эти дампы гораздо приятнее читать, это не подходит для больших дампов > 1 ГБ, потому что оно имеет тенденцию быть очень медленным
- создать дамп с расширенными вставками (который по умолчанию), но ограничить net-buffer_length, например. с —net-buffer_length NR_OF_BYTES где NR_OF_BYTES меньше, чем сервер net_buffer_length → Я думаю, что это лучшее решение, хотя медленнее перезагрузка сервера не требуется.
Я использовал следующую команду mysqldump: mysqldump —skip-comments —set-charset —default-character-set=utf8 —single-transaction —net-buffer_length 4096 DBX > dumpfile
Ответ 14
У меня возникла такая же проблема при загрузке CSV файла. Преобразовал файл в .sql.
Используя команду ниже, мне удается обойти эту проблему.
Надеюсь, это поможет.
Ответ 15
Если все остальные решения здесь не работают — проверьте ваш syslog (/var/log/syslog или аналогичный), чтобы узнать, не исчерпан ли ваш сервер во время запроса.
Если эта проблема возникла, когда innodb_buffer_pool_size был установлен слишком близко к физической памяти без настроенного файла подкачки. MySQL рекомендует для определенного сервера базы данных innodb_buffer_pool_size максимум около 80% физической памяти, я установил его около 90%, Ядро убивало процесс mysql. Перемещенный файл innodb_buffer_pool_size возвращается примерно до 80%, и это устраняет проблему.
Ответ 16
Я столкнулся с этой же проблемой. Я считаю, что это происходит, когда у вас есть внешние ключи для больших таблиц (что требует времени).
Я попытался снова запустить инструкцию create table без объявлений внешнего ключа и нашел, что это сработало.
Затем после создания таблицы я добавил ограничения внешнего ключа, используя запрос ALTER TABLE.
Надеюсь, это поможет кому-то.
Ответ 17
Это произошло со мной, потому что мой innodb_buffer_pool_size был установлен больше, чем размер оперативной памяти, доступный на сервере. Из-за этого все из-за этого прерывается, и эта ошибка возникает. Исправление состоит в том, чтобы обновить my.cnf с правильной настройкой для innodb_buffer_pool_size.
Ответ 18
Перейдите в Workbench Edit → Preferences → SQL Editor → Время ожидания подключения к СУБД: до 3000. Ошибка больше не возникает.
Ответ 19
Изменить → Настройки → Редактор SQL
Здесь вы можете увидеть три поля в группе «Сессия MySQL», где теперь вы можете установить новые интервалы подключения (в секундах).
Ответ 20
Оказывается, наше правило брандмауэра блокирует мое подключение к MYSQL. После того, как политика брандмауэра отменена, чтобы разрешить соединение, я смог успешно импортировать схему.
Ответ 21
У меня была такая же проблема — но для меня решение было пользователем БД со слишком строгими разрешениями. Я должен был разрешить возможность Execute в таблице mysql . После того, как разрешилось, что у меня больше не было отбрасываемых соединений
Ответ 22
Проверьте, установлены ли индексы.
Ответ 23
Я столкнулся с этим при запуске сохраненного proc-, который создавал много строк в таблице в базе данных. Я мог видеть, что ошибка наступила сразу после того, как время пересекло границу 30 секунд.
Я попробовал все предложения в других ответах. Я уверен, что некоторые из них помогли, however-, что действительно заставило его работать для меня, это переход на SequelPro из Workbench.
Я предполагаю, что это была некоторая клиентская связь, которую я не мог обнаружить в Workbench. Может быть, это тоже поможет кому-то другому?
Ответ 24
Если вы используете SQL Work Bench, вы можете попробовать использовать индексирование, добавив индекс в свои таблицы, добавить индекс, нажать на гаечный ключ (гаечный ключ) в таблице, он должен открыть настройку для таблицы, ниже, нажмите на индексный указатель, введите имя индекса и установите индекс для индекса. В столбцах индекса выберите основной столбец в своей таблице.
Сделайте тот же шаг для других первичных ключей на других таблицах.
Ответ 25
Кажется, здесь нет ответа для тех, кто использует SSH для подключения к своей базе данных MySQL. Вам нужно проверить два места, а не 1, как предлагают другие ответы:
Редактирование рабочей среды → Настройки → Редактор SQL → СУБД
Рабочее место Правка → Настройки → SSH → Тайм-ауты
Мои тайм-ауты SSH по умолчанию были установлены очень низкими и вызывали некоторые (но, очевидно, не все) мои проблемы тайм-аута. После, не забудьте перезапустить MySQL Workbench!
Наконец, возможно, стоит обратиться к администратору БД и попросить его увеличить свойства wait_timeout и interactive_timeout в самом mysql через my.conf + mysql restart или выполнить глобальный набор, если перезапуск mysql не является опцией.
Надеюсь это поможет!
Ответ 26
Три вещи, которым нужно следовать и убедитесь:
- Если несколько запросов показывают потерянное соединение?
- как вы используете набор запросов в MySQL?
- как удалить + обновить запрос одновременно?
- Всегда пытайтесь удалить определитель, поскольку MySQL создает свой собственный определитель, и если несколько таблиц, участвующих в обновлении, пытаются сделать один запрос, так как иногда несколько запросов показывают потерянное соединение
- Всегда устанавливайте значение сверху, но после УДАЛИТЬ, если его условие не включает значение SET.
- Используйте УДАЛИТЬ ПЕРВЫЕ, ТОГДА ОБНОВЛЕНИЯ, ЕСЛИ ОБА ИХ ОПЕРАЦИИ ИСПОЛЬЗУЮТСЯ НА РАЗНЫХ ТАБЛИЦАХ
Ответ 27
Надеюсь, что это поможет
Ответ 28
Это обычно означает, что у вас есть «несовместимости с текущей версией MySQL Server», см. mysql_upgrade. Я столкнулся с этой проблемой и просто должен был работать:
mysql_upgrade —password В документации указано, что «mysql_upgrade должен выполняться каждый раз при обновлении MySQL».
Источник
Код ошибки: 2013. Потерянное соединение с сервером MySQL во время запроса
Я получил код Код ошибки: 2013. Потерянное подключение к MySQL-серверу во время запроса при попытке добавить индекс в таблицу с помощью MySQL Workbench. Я также заметил, что он появляется, когда я запускаю длинный запрос.
Есть ли возможность увеличить значение таймаута?
ОТВЕТЫ
Ответ 1
Новые версии MySQL WorkBench имеют возможность изменять определенные тайм-ауты.
Для меня это было в разделе Редактировать → Настройки → Редактор SQL → Время ожидания подключения к СУБД (в секундах): 600
Изменено значение до 6000.
Также не проверенные предельные строки, как ограничение лимита в каждый раз, когда я хочу искать весь набор данных, становятся утомительными.
Ответ 2
Запустите сервер БД с помощью опции comandline net_read_timeout / wait_timeout и подходящего значения (в секундах) — например: —net_read_timeout=100 .
Для справки см. здесь и здесь.
Ответ 3
Если у вашего запроса есть данные blob, эту проблему можно устранить, применив my.ini change как предлагается в этом ответе:
По умолчанию это будет 1M (допустимое максимальное значение равно 1024M). Если заданное значение не кратно 1024 КБ, оно будет автоматически округлено до ближайшего кратного 1024 КБ.
В то время как связанный поток относится к ошибке MySQL 2006 года, установка max_allowed_packet с 1M до 16M исправила ошибку 2013, которая появилась для меня при запуске длинного запроса.
Для пользователей WAMP: вы найдете флаг в разделе [wampmysqld] .
Ответ 4
Добавьте в файл /etc/mysql/cnf следующее:
Ответ 5
Предупреждение. Следующие действия не будут работать, если вы применяете его в удаленном соединении:
Ответ 6
Для этого сообщения об ошибке есть три причины
- Обычно это указывает на проблемы с подключением к сети, и вы должны проверить состояние своей сети, если эта ошибка возникает часто
- Иногда форма «во время запроса» возникает, когда миллионы строк отправляются как часть одного или нескольких запросов.
- Реже это может произойти, когда клиент пытается выполнить первоначальное подключение к серверу
от значения по умолчанию от 30 секунд до 60 секунд или дольше
Ответ 7
Вы должны установить свойства «interactive_timeout» и «wait_timeout» в файле конфигурации mysql для значений, которые вам нужны.
Ответ 8
Спасибо, это сработало. Но с обновлениями mysqldb настройка стала:
Ответ 9
Просто выполните обновление MySQL, которое будет перестроить механизм innoDB вместе с перестройкой многих таблиц, необходимых для правильной работы MySQL, таких как performance_schema , information_schema и т.д.
Выпустите следующую команду из своей оболочки:
Ответ 10
Я знаю его старый, но на mac
Ответ 11
Измените время ожидания чтения в Edit- > Preferences- > SQL-редакторе- > сеансе MySQL
Ответ 12
Попробуйте снять флажки с ограничениями строк в разделе «Редактировать» → «Настройки» → «Запросы SQL»
потому что вы должны установить свойства «interactive_timeout» и «wait_timeout» в конфигурационном файле mysql для значений, которые вам нужны.
Ответ 13
Если вы столкнулись с этой проблемой во время восстановления большого файла дампа и можете исключить проблему, связанную с сетью (например, выполнение на локальном хосте), может оказаться полезным мое решение.
Мой mysqldump провел хотя бы один INSERT, который был слишком большим для вычисления mysql. Вы можете просмотреть эту переменную, набрав show variables like «net_buffer_length»; внутри вашего mysql-cli. У вас есть три возможности:
- увеличить net_buffer_length внутри mysql → для этого потребуется перезагрузка сервера
- создать дамп с —skip-extended-insert , для каждой вставки используется одна строка → хотя эти дампы гораздо приятнее читать, это не подходит для больших дампов > 1 ГБ, потому что оно имеет тенденцию быть очень медленным
- создать дамп с расширенными вставками (который по умолчанию), но ограничить net-buffer_length, например. с —net-buffer_length NR_OF_BYTES где NR_OF_BYTES меньше, чем сервер net_buffer_length → Я думаю, что это лучшее решение, хотя медленнее перезагрузка сервера не требуется.
Я использовал следующую команду mysqldump: mysqldump —skip-comments —set-charset —default-character-set=utf8 —single-transaction —net-buffer_length 4096 DBX > dumpfile
Ответ 14
У меня возникла такая же проблема при загрузке CSV файла. Преобразовал файл в .sql.
Используя команду ниже, мне удается обойти эту проблему.
Надеюсь, это поможет.
Ответ 15
Если все остальные решения здесь не работают — проверьте ваш syslog (/var/log/syslog или аналогичный), чтобы узнать, не исчерпан ли ваш сервер во время запроса.
Если эта проблема возникла, когда innodb_buffer_pool_size был установлен слишком близко к физической памяти без настроенного файла подкачки. MySQL рекомендует для определенного сервера базы данных innodb_buffer_pool_size максимум около 80% физической памяти, я установил его около 90%, Ядро убивало процесс mysql. Перемещенный файл innodb_buffer_pool_size возвращается примерно до 80%, и это устраняет проблему.
Ответ 16
Я столкнулся с этой же проблемой. Я считаю, что это происходит, когда у вас есть внешние ключи для больших таблиц (что требует времени).
Я попытался снова запустить инструкцию create table без объявлений внешнего ключа и нашел, что это сработало.
Затем после создания таблицы я добавил ограничения внешнего ключа, используя запрос ALTER TABLE.
Надеюсь, это поможет кому-то.
Ответ 17
Это произошло со мной, потому что мой innodb_buffer_pool_size был установлен больше, чем размер оперативной памяти, доступный на сервере. Из-за этого все из-за этого прерывается, и эта ошибка возникает. Исправление состоит в том, чтобы обновить my.cnf с правильной настройкой для innodb_buffer_pool_size.
Ответ 18
Перейдите в Workbench Edit → Preferences → SQL Editor → Время ожидания подключения к СУБД: до 3000. Ошибка больше не возникает.
Ответ 19
Изменить → Настройки → Редактор SQL
Здесь вы можете увидеть три поля в группе «Сессия MySQL», где теперь вы можете установить новые интервалы подключения (в секундах).
Ответ 20
Оказывается, наше правило брандмауэра блокирует мое подключение к MYSQL. После того, как политика брандмауэра отменена, чтобы разрешить соединение, я смог успешно импортировать схему.
Ответ 21
У меня была такая же проблема — но для меня решение было пользователем БД со слишком строгими разрешениями. Я должен был разрешить возможность Execute в таблице mysql . После того, как разрешилось, что у меня больше не было отбрасываемых соединений
Ответ 22
Проверьте, установлены ли индексы.
Ответ 23
Я столкнулся с этим при запуске сохраненного proc-, который создавал много строк в таблице в базе данных. Я мог видеть, что ошибка наступила сразу после того, как время пересекло границу 30 секунд.
Я попробовал все предложения в других ответах. Я уверен, что некоторые из них помогли, however-, что действительно заставило его работать для меня, это переход на SequelPro из Workbench.
Я предполагаю, что это была некоторая клиентская связь, которую я не мог обнаружить в Workbench. Может быть, это тоже поможет кому-то другому?
Ответ 24
Если вы используете SQL Work Bench, вы можете попробовать использовать индексирование, добавив индекс в свои таблицы, добавить индекс, нажать на гаечный ключ (гаечный ключ) в таблице, он должен открыть настройку для таблицы, ниже, нажмите на индексный указатель, введите имя индекса и установите индекс для индекса. В столбцах индекса выберите основной столбец в своей таблице.
Сделайте тот же шаг для других первичных ключей на других таблицах.
Ответ 25
Кажется, здесь нет ответа для тех, кто использует SSH для подключения к своей базе данных MySQL. Вам нужно проверить два места, а не 1, как предлагают другие ответы:
Редактирование рабочей среды → Настройки → Редактор SQL → СУБД
Рабочее место Правка → Настройки → SSH → Тайм-ауты
Мои тайм-ауты SSH по умолчанию были установлены очень низкими и вызывали некоторые (но, очевидно, не все) мои проблемы тайм-аута. После, не забудьте перезапустить MySQL Workbench!
Наконец, возможно, стоит обратиться к администратору БД и попросить его увеличить свойства wait_timeout и interactive_timeout в самом mysql через my.conf + mysql restart или выполнить глобальный набор, если перезапуск mysql не является опцией.
Надеюсь это поможет!
Ответ 26
Три вещи, которым нужно следовать и убедитесь:
- Если несколько запросов показывают потерянное соединение?
- как вы используете набор запросов в MySQL?
- как удалить + обновить запрос одновременно?
- Всегда пытайтесь удалить определитель, поскольку MySQL создает свой собственный определитель, и если несколько таблиц, участвующих в обновлении, пытаются сделать один запрос, так как иногда несколько запросов показывают потерянное соединение
- Всегда устанавливайте значение сверху, но после УДАЛИТЬ, если его условие не включает значение SET.
- Используйте УДАЛИТЬ ПЕРВЫЕ, ТОГДА ОБНОВЛЕНИЯ, ЕСЛИ ОБА ИХ ОПЕРАЦИИ ИСПОЛЬЗУЮТСЯ НА РАЗНЫХ ТАБЛИЦАХ
Ответ 27
Надеюсь, что это поможет
Ответ 28
Это обычно означает, что у вас есть «несовместимости с текущей версией MySQL Server», см. mysql_upgrade. Я столкнулся с этой проблемой и просто должен был работать:
mysql_upgrade —password В документации указано, что «mysql_upgrade должен выполняться каждый раз при обновлении MySQL».
Источник
November 4, 2017 | Posted in SQL
This is kind of a silly and duplicative post, but I spent too much time searching for the right answer, so maybe this will help the right course of action bubble to the top faster in the future.
The Issue
I was trying to run a query on my local SQL install (whatever MAMP manages and provisions) using MySQL Workbench 6.3 for Mac but kept getting a timeout error.
The query itself wasn’t overly complex, but I was using aggregate functions, group by, and a join to consolidate a dataset. I’m working with distance education reporting data for all U.S. colleges and universities from 2012-2015, so this join involved a 7K row table and another with 25K rows, so not inconsequential but also not BIG data level.
SELECT STABBR as State, EFDELEV as Level , SUM(EFDETOT) as Total_Distance, SUM(EFDEEXC) as Exclusive_Distance, SUM(EFDESOM) as Some_Distance, SUM(EFDENON) as None_Distance FROM hd2012 LEFT JOIN ef2012a_dist_rv ON hd2012.UNITID = ef2012a_dist_rv.UNITID GROUP BY State, Level;
I did some initial googling on the error code, but it is a pretty general error code, so it was difficult to be sure whether this was a limitation of SQL or the Workbench DBMS. I read a few posts that suggested manipulating some of the .conf files for the underlying MySQL install, and I went too long down this road before trying something in Workbench itself.
It turns out there are timeout settings for the DBMS that you extend to make sure that it waits a sufficient amount of time for your query to return data. Thanks to this specific answer on StackOverflow, but the description of “how-to” it links to is no longer valid, hence this blog post.
The Fix
There is a quick setting in Preferences that helped me. As you might expect, the DBMS has settings to manage its connection to the SQL server. In my case, those were just too short for my long running queries.
I changed the 30 second defaults to 180, and returned the data I needed. However, I’d imagine that some things would call for a much higher timeout, especially if you wanted to do a lot of transactions.
Another Fix
As of 08/27/2018, I did some additional noodling around with the queries that produced this slow result and realized some simple indexing reduced the query time from ~50 seconds to .227 seconds. You can find a more detailed post about that here.
If you are looking for a way to stop the timeout error, now you have two options. However, now I realize that most of my issue had nothing to do with MySQL Workbench and everything to do with the way I constructed the underlying database : ) However, options are always good, so good luck!
Я получил код Код ошибки: 2013. Потерянное подключение к MySQL-серверу во время запроса при попытке добавить индекс в таблицу с помощью MySQL Workbench.
Я также заметил, что он появляется, когда я запускаю длинный запрос.
Есть ли возможность увеличить значение таймаута?
Ответ 1
Новые версии MySQL WorkBench имеют возможность изменять определенные тайм-ауты.
Для меня это было в разделе Редактировать → Настройки → Редактор SQL → Время ожидания подключения к СУБД (в секундах): 600
Изменено значение до 6000.
Также не проверенные предельные строки, как ограничение лимита в каждый раз, когда я хочу искать весь набор данных, становятся утомительными.
Ответ 2
Запустите сервер БД с помощью опции comandline net_read_timeout
/wait_timeout
и подходящего значения (в секундах) — например: --net_read_timeout=100
.
Для справки см. здесь и здесь.
Ответ 3
Если у вашего запроса есть данные blob, эту проблему можно устранить, применив my.ini
change как предлагается в этом ответе:
[mysqld]
max_allowed_packet=16M
По умолчанию это будет 1M (допустимое максимальное значение равно 1024M). Если заданное значение не кратно 1024 КБ, оно будет автоматически округлено до ближайшего кратного 1024 КБ.
В то время как связанный поток относится к ошибке MySQL 2006 года, установка max_allowed_packet
с 1M до 16M исправила ошибку 2013, которая появилась для меня при запуске длинного запроса.
Для пользователей WAMP: вы найдете флаг в разделе [wampmysqld]
.
Ответ 4
Добавьте в файл /etc/mysql/cnf следующее:
innodb_buffer_pool_size = 64M
Пример:
key_buffer = 16M
max_allowed_packet = 16M
thread_stack = 192K
thread_cache_size = 8
innodb_buffer_pool_size = 64M
Ответ 5
SET @@local.net_read_timeout=360;
Предупреждение. Следующие действия не будут работать, если вы применяете его в удаленном соединении:
SET @@global.net_read_timeout=360;
Ответ 6
Для этого сообщения об ошибке есть три причины
- Обычно это указывает на проблемы с подключением к сети, и вы должны проверить состояние своей сети, если эта ошибка возникает часто
- Иногда форма «во время запроса» возникает, когда миллионы строк отправляются как часть одного или нескольких запросов.
- Реже это может произойти, когда клиент пытается выполнить первоначальное подключение к серверу
Для более подробной информации >>
Причина 2:
SET GLOBAL interactive_timeout=60;
от значения по умолчанию от 30 секунд до 60 секунд или дольше
Причина 3:
SET GLOBAL connect_timeout=60;
Ответ 7
Вы должны установить свойства «interactive_timeout» и «wait_timeout» в файле конфигурации mysql для значений, которые вам нужны.
Ответ 8
Спасибо, это сработало.
Но с обновлениями mysqldb настройка стала:
max_allowed_packet
net_write_timeout
net_read_timeout
mysql doc
Ответ 9
Просто выполните обновление MySQL, которое будет перестроить механизм innoDB вместе с перестройкой многих таблиц, необходимых для правильной работы MySQL, таких как performance_schema
, information_schema
и т.д.
Выпустите следующую команду из своей оболочки:
sudo mysql_upgrade -u root -p
Ответ 10
Я знаю его старый, но на mac
1. Control-click your connection and choose Connection Properties.
2. Under Advanced tab, set the Socket Timeout (sec) to a larger value.
Ответ 11
Измените время ожидания чтения в Edit- > Preferences- > SQL-редакторе- > сеансе MySQL
Ответ 12
Попробуйте снять флажки с ограничениями строк в разделе «Редактировать» → «Настройки» → «Запросы SQL»
потому что вы должны установить свойства «interactive_timeout» и «wait_timeout» в конфигурационном файле mysql для значений, которые вам нужны.
Ответ 13
Если вы столкнулись с этой проблемой во время восстановления большого файла дампа и можете исключить проблему, связанную с сетью (например, выполнение на локальном хосте), может оказаться полезным мое решение.
Мой mysqldump провел хотя бы один INSERT, который был слишком большим для вычисления mysql. Вы можете просмотреть эту переменную, набрав show variables like "net_buffer_length";
внутри вашего mysql-cli.
У вас есть три возможности:
- увеличить net_buffer_length внутри mysql → для этого потребуется перезагрузка сервера
- создать дамп с
--skip-extended-insert
, для каждой вставки используется одна строка → хотя эти дампы гораздо приятнее читать, это не подходит для больших дампов > 1 ГБ, потому что оно имеет тенденцию быть очень медленным - создать дамп с расширенными вставками (который по умолчанию), но ограничить net-buffer_length, например. с
--net-buffer_length NR_OF_BYTES
где NR_OF_BYTES меньше, чем сервер net_buffer_length → Я думаю, что это лучшее решение, хотя медленнее перезагрузка сервера не требуется.
Я использовал следующую команду mysqldump: mysqldump --skip-comments --set-charset --default-character-set=utf8 --single-transaction --net-buffer_length 4096 DBX > dumpfile
Ответ 14
У меня возникла такая же проблема при загрузке CSV файла.
Преобразовал файл в .sql.
Используя команду ниже, мне удается обойти эту проблему.
mysql -u <user> -p -D <DB name> < file.sql
Надеюсь, это поможет.
Ответ 15
Если все остальные решения здесь не работают — проверьте ваш syslog (/var/log/syslog или аналогичный), чтобы узнать, не исчерпан ли ваш сервер во время запроса.
Если эта проблема возникла, когда innodb_buffer_pool_size был установлен слишком близко к физической памяти без настроенного файла подкачки. MySQL рекомендует для определенного сервера базы данных innodb_buffer_pool_size максимум около 80% физической памяти, я установил его около 90%, Ядро убивало процесс mysql. Перемещенный файл innodb_buffer_pool_size возвращается примерно до 80%, и это устраняет проблему.
Ответ 16
Я столкнулся с этой же проблемой. Я считаю, что это происходит, когда у вас есть внешние ключи для больших таблиц (что требует времени).
Я попытался снова запустить инструкцию create table без объявлений внешнего ключа и нашел, что это сработало.
Затем после создания таблицы я добавил ограничения внешнего ключа, используя запрос ALTER TABLE.
Надеюсь, это поможет кому-то.
Ответ 17
Это произошло со мной, потому что мой innodb_buffer_pool_size был установлен больше, чем размер оперативной памяти, доступный на сервере. Из-за этого все из-за этого прерывается, и эта ошибка возникает. Исправление состоит в том, чтобы обновить my.cnf с правильной настройкой для innodb_buffer_pool_size.
Ответ 18
Перейдите в Workbench Edit → Preferences → SQL Editor → Время ожидания подключения к СУБД: до 3000. Ошибка больше не возникает.
Ответ 19
Перейдите к:
Изменить → Настройки → Редактор SQL
Здесь вы можете увидеть три поля в группе «Сессия MySQL», где теперь вы можете установить новые интервалы подключения (в секундах).
Ответ 20
Оказывается, наше правило брандмауэра блокирует мое подключение к MYSQL. После того, как политика брандмауэра отменена, чтобы разрешить соединение, я смог успешно импортировать схему.
Ответ 21
У меня была такая же проблема — но для меня решение было пользователем БД со слишком строгими разрешениями.
Я должен был разрешить возможность Execute
в таблице mysql
. После того, как разрешилось, что у меня больше не было отбрасываемых соединений
Ответ 22
Проверьте, установлены ли индексы.
SELECT *
FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA = '<schema>'
Ответ 23
Я столкнулся с этим при запуске сохраненного proc-, который создавал много строк в таблице в базе данных. Я мог видеть, что ошибка наступила сразу после того, как время пересекло границу 30 секунд.
Я попробовал все предложения в других ответах. Я уверен, что некоторые из них помогли, however-, что действительно заставило его работать для меня, это переход на SequelPro из Workbench.
Я предполагаю, что это была некоторая клиентская связь, которую я не мог обнаружить в Workbench. Может быть, это тоже поможет кому-то другому?
Ответ 24
Если вы используете SQL Work Bench, вы можете попробовать использовать индексирование, добавив индекс в свои таблицы, добавить индекс, нажать на гаечный ключ (гаечный ключ) в таблице, он должен открыть настройку для таблицы, ниже, нажмите на индексный указатель, введите имя индекса и установите индекс для индекса. В столбцах индекса выберите основной столбец в своей таблице.
Сделайте тот же шаг для других первичных ключей на других таблицах.
Ответ 25
Кажется, здесь нет ответа для тех, кто использует SSH для подключения к своей базе данных MySQL. Вам нужно проверить два места, а не 1, как предлагают другие ответы:
Редактирование рабочей среды → Настройки → Редактор SQL → СУБД
Рабочее место Правка → Настройки → SSH → Тайм-ауты
Мои тайм-ауты SSH по умолчанию были установлены очень низкими и вызывали некоторые (но, очевидно, не все) мои проблемы тайм-аута. После, не забудьте перезапустить MySQL Workbench!
Наконец, возможно, стоит обратиться к администратору БД и попросить его увеличить свойства wait_timeout и interactive_timeout в самом mysql через my.conf + mysql restart или выполнить глобальный набор, если перезапуск mysql не является опцией.
Надеюсь это поможет!
Ответ 26
Три вещи, которым нужно следовать и убедитесь:
- Если несколько запросов показывают потерянное соединение?
- как вы используете набор запросов в MySQL?
- как удалить + обновить запрос одновременно?
Ответы:
- Всегда пытайтесь удалить определитель, поскольку MySQL создает свой собственный определитель, и если несколько таблиц, участвующих в обновлении, пытаются сделать один запрос, так как иногда несколько запросов показывают потерянное соединение
- Всегда устанавливайте значение сверху, но после УДАЛИТЬ, если его условие не включает значение SET.
- Используйте УДАЛИТЬ ПЕРВЫЕ, ТОГДА ОБНОВЛЕНИЯ, ЕСЛИ ОБА ИХ ОПЕРАЦИИ ИСПОЛЬЗУЮТСЯ НА РАЗНЫХ ТАБЛИЦАХ
Ответ 27
проверить
OOM on /var/log/messages ,
modify innodb_buffer_pool_size value ; when load data , use 50% of os mem ;
Надеюсь, что это поможет
Ответ 28
Это обычно означает, что у вас есть «несовместимости с текущей версией MySQL Server», см. mysql_upgrade. Я столкнулся с этой проблемой и просто должен был работать:
mysql_upgrade —password
В документации указано, что «mysql_upgrade должен выполняться каждый раз при обновлении MySQL».
When you run MySQL queries, sometimes you may encounter an error saying you lost connection to the MySQL server as follows:
Error Code: 2013. Lost connection to MySQL server during query
The error above commonly happens when you run a long or complex MySQL query that runs for more than a few seconds.
To fix the error, you may need to change the timeout-related global settings in your MySQL database server.
Increase the connection timeout from the command line using –connect-timeout option
If you’re accessing MySQL from the command line, then you can increase the number of seconds MySQL will wait for a connection response using the --connect-timeout
option.
By default, MySQL will wait for 10 seconds before responding with a connection timeout error.
You can increase the number to 120 seconds to wait for two minutes:
mysql -uroot -proot --connect-timeout 120
You can adjust the number 120
above to the number of seconds you’d like to wait for a connection response.
Once you’re inside the mysql
console, try running your query again to see if it’s completed successfully.
Using the --connect-timeout
option changes the timeout seconds temporarily. It only works for the current MySQL session you’re running, so you need to use the option each time you want the connection timeout to be longer.
If you want to make a permanent change to the connection timeout variable, then you need to adjust the settings from either your MySQL database server or the GUI tool you used to access your database server.
Let’s see how to change the timeout global variables in your MySQL database server first.
Adjust the timeout global variables in your MySQL database server
MySQL database stores timeout-related global variables that you can access using the following query:
SHOW VARIABLES LIKE "%timeout";
Here’s the result from my local database. The highlighted variables are the ones you need to change to let MySQL run longer queries:
+-----------------------------------+----------+
| Variable_name | Value |
+-----------------------------------+----------+
| connect_timeout | 10 |
| delayed_insert_timeout | 300 |
| have_statement_timeout | YES |
| innodb_flush_log_at_timeout | 1 |
| innodb_lock_wait_timeout | 50 |
| innodb_rollback_on_timeout | OFF |
| interactive_timeout | 28800 |
| lock_wait_timeout | 31536000 |
| mysqlx_connect_timeout | 30 |
| mysqlx_idle_worker_thread_timeout | 60 |
| mysqlx_interactive_timeout | 28800 |
| mysqlx_port_open_timeout | 0 |
| mysqlx_read_timeout | 30 |
| mysqlx_wait_timeout | 28800 |
| mysqlx_write_timeout | 60 |
| net_read_timeout | 30 |
| net_write_timeout | 60 |
| replica_net_timeout | 60 |
| rpl_stop_replica_timeout | 31536000 |
| rpl_stop_slave_timeout | 31536000 |
| slave_net_timeout | 60 |
| wait_timeout | 28800 |
+-----------------------------------+----------+
To change the variable values, you can use the SET GLOBAL
query as shown below:
SET GLOBAL connect_timeout = 600;
The above query should adjust the connect_timeout
variable value to 600
seconds. You can adjust the numbers as you see fit.
Adjust the timeout variables in your MySQL configuration files
Alternatively, if you’re using a MySQL configuration file to control the settings of your connections, then you can edit the my.cnf file (Mac) or my.ini file (Windows) used by your MySQL connection.
Open that configuration file using the text editor of your choice and try to find the following variables in mysqld :
[mysqld]
connect_timeout = 10
net_read_timeout = 30
wait_timeout = 28800
interactive_timeout = 28800
The wait_timeout
and interactive_timeout
variables shouldn’t cause any problem because they usually have 28800 seconds (or 8 hours) as their default value.
To prevent the timeout error, you need to increase the connect_timeout
and net_read_timeout
variable values. I’d suggest setting it to at least 600
seconds (10 minutes)
If you’re using GUI MySQL tools like MySQL Workbench, Sequel Ace, or PHPMyAdmin, then you can also find timeout-related variables that are configured by these tools in their settings or preferences menu.
For example, in MySQL Workbench for Windows, you can find the timeout-related settings in Edit > Preferences > SQL Editor as shown below:
If you’re using Mac, then the menu should be in MySQLWorkbench > Preferences > SQL Editor as shown below:
If you’re using Sequel Ace like me, then you can find the connection timeout option in the Preferences > Network menu.
Here’s a screenshot from Sequel Ace Network settings:
For other GUI tools, you need to find the option yourself. You can try searching the term [tool name] connection timeout settings
in Google to find the option.
And those are the four solutions you can try to fix the MySQL connection lost during query issue.
I hope this tutorial has been helpful for you 🙏