当前位置:网站首页>MySQL case
MySQL case
2022-07-04 09:47:00 【Stestack】
list MySQL The ten most classic error cases in database , And the solutions to the problems are attached , In the future, there will be any error reports . Learning any technology at the same time , In fact, it is the process of self-cultivation , heavy , Try to embrace the world of data !
Case a
Too many connections
( Too many connections , Cause no connection to database , Business can't go on )
Problem reduction :
mysql> show variables like ‘%max_connection%’;
| Variable_name | Value |
max_connections | 151 |
mysql> set global max_connections=1;Query OK, 0 rows affected (0.00 sec)
[[email protected] ~]# mysql -uzs -p123456 -h 192.168.56.132
ERROR 1040 (00000): Too many connections
Solutions to problems :
1、 First of all, we should consider MySQL In the database parameter file , Corresponding max_connections Is this parameter set too small , The result is that the number of client connections exceeds the maximum number of database connections .
The default size for this value is 151, We can adjust it according to the actual situation .
The corresponding solution :set global max_connections=500
But there are hidden dangers in this adjustment , Because we can't confirm whether the database can bear the connection pressure , React to the server , There is a possibility of downtime . So this again reflects , When we launch a new business system , Do a stress test . Make sure to optimize the database later .
2、 Secondly, we can limit InnoDB The number of concurrent processing , If innodb_thread_concurrency = 0( There is no limit to this representation ) It can be changed to 16 or 64 Look at the server pressure .
If it's very big , You can change it a little bit to make the server under pressure , And then slowly increase , Depending on your business , My personal suggestion can be adjusted to 16 that will do .
MySQL As the number of connections increases, the performance will decrease , stay MySQL 5.7 Before all need to let the development match the setting thread pool, Connection reuse .MySQL 5.7 Then the database comes with it thread pool 了 , The connection number problem is also solved .
In addition, some monitoring programs will read information_schema The table below , Consider turning off the following parameters :
innodb_stats_on_metadata=0
set global innodb_stats_on_metadata=0
Case 2
Master slave copy error type
Last_SQL_Errno: 1062 ( Data conflict between slave library and master library )
Last_Errno: 1062
Last_Error: Could not execute Write_rows event on table test.t;
Duplicate entry ‘4’ for key ‘PRIMARY’,
Error_code: 1062; handler error HA_ERR_FOUND_DUPP_KEY;
the event’s master log mysql-bin.000014, end_log_pos 1505
For this error report , We should first consider whether it is caused by misoperation from the library . Results found , We made a query from the library for the primary key table SQL Statement insertion , Causes the main database to be inserted again sql When , The master-slave state is abnormal . An error is reported in case of primary key conflict .
resolvent : On the premise of ensuring the consistency of master-slave data , You can do error skipping from the library . In general use percona-toolkit Medium pt-slave-restart Conduct .
Complete the following operations in the slave library :
[[email protected] bin]# ./pt-slave-restart -uroot -proot123
2021-07-20T14:05:30 p=…,u=root node4-relay-bin.000002 1506 1062
After that, it's better to open it from the library read_only Parameters , It is forbidden to write from the library .
Last_IO_Errno: 1593(server-id Conflict )
Last_IO_Error:
Fatal error: The slave I/O thread stops because master and slave have equal MySQL server ids;
these ids must be different for replication to work
(or the –replicate-same-server-id option must be used on slave but this
does not always make sense; please check the manual before using it)
After this error report , You can see two machines at a glance server-id It's the same .
In the process of building master-slave replication , We need to make sure that the two machines are server-id Is the only one. . Here's another point server-id Naming rules ( The server ip The last digit of the address + Ben MySQL The port number of the service ).
resolvent : Set different... On the master and slave machines server-id.
Last_SQL_Errno: 1032( From less data base , When the main library is updated , Report an error from the library )
Last_SQL_Error:
Could not execute Update_rows event on table test.t; Can’t find record
in ‘t’, Error_code: 1032; handler error HA_ERR_KEY_NOT_FOUND; the
event’s master log mysql-bin.000014, end_log_pos 1708
The solution to the problem : According to the error information , We can get error logs and position Number , Then you can find out which one the main library performs sql, Leading to the master-slave error .
Execute... In the main library :
/usr/local/mysql/bin/mysqlbinlog –no-defaults -v -v –base64-output=decode-rows /data/mysql/mysql-bin.000014 |grep -A 10 1708 > 1.log
cat 1.log
#170720 14:20:15 server id 3 end_log_pos 1708 CRC32 0x97b6bdec Update_rows: table id 113 flags: STMT_END_F
### UPDATE `test`.`t`
### WHERE
### @1=4 /* INT meta=0 nullable=0 is_null=0 */
### @2=’dd’ /* VARSTRING(60) meta=60 nullable=1 is_null=0 */
### SET
### @1=4 /* INT meta=0 nullable=0 is_null=0 */
### @2=’ddd’ /* VARSTRING(60) meta=60 nullable=1 is_null=0 */
# at 1708
#170720 14:20:15 server id 3 end_log_pos 1739 CRC32 0xecaf1922 Xid = 654
COMMIT/*!*/;
DELIMITER ;
# End of log file
ROLLBACK /* added by mysqlbinlog */;
/*!50003 SET [email protected]_COMPLETION_TYPE*/;
/*!50530 SET @@SESSION.PSEUDO_SLAVE_MODE=0*/;
Get SQL After statement , It can be executed in reverse from the library SQL sentence . Take what's missing from the library SQL Sentence completion , Solve the error message .
In order to execute from the library :
mysql> insert into t (b) values (‘ddd’);
Query OK, 1 row affected (0.01 sec)
mysql> stop slave;
Query OK, 0 rows affected (0.00 sec)
mysql> exit
Bye
[[email protected] bin]# ./pt-slave-restart -uroot -proot1232017-07-20T14:31:37 p=…,u=root node4-relay-bin.000005 283 1032
Case three
MySQL Error report during installation
[[email protected] data]# /usr/local/mysql/bin/mysqld_safe –defaults-file=/etc/my.cnf &[1] 3758
[[email protected] data]# 170720 14:41:24 mysqld_safe Logging to ‘/data/mysql/error.log’.
170720 14:41:24 mysqld_safe Starting mysqld daemon with databases from /data/mysql170720
14:41:25 mysqld_safe mysqld from pid file /data/mysql/node4.pid ended
170720 14:41:24 mysqld_safe Starting mysqld daemon with databases from /data/mysql2017-07-20
14:41:25 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated.
Please use –explicit_defaults_for_timestamp server option
(see documentation for more details)./usr/local/mysql/bin/mysqld:
File ‘/data/mysql/mysql-bin.index’ not found (Errcode: 13 – Permission denied)
2017-07-20 14:41:25 4388 [ERROR] Aborting
Solutions : In case of such an error message , We should learn to pay attention to the error log from time to time error log What's in it . See the key error reporting points Permission denied, Prove the present MySQL The data directory of the database has no permissions .
resolvent :
[[email protected] data]# chown mysql:mysql -R mysql
[[email protected] data]# /usr/local/mysql/bin/mysqld_safe –defaults-file=/etc/my.cnf &
[1] 4402
[[email protected] data]# 170720 14:45:56 mysqld_safe Logging to ‘/data/mysql/error.log’.
170720 14:45:56 mysqld_safe Starting mysqld daemon with databases from /data/mysql
Successful launch .
How to avoid such problems , I suggest that you install MySQL When initializing , It must be added –user=mysql, In this way, the problem of permissions can be avoided .
./mysql_install_db –basedir=/usr/local/mysql/ –datadir=/data/mysql/ –defaults-file=/etc/my.cnf –user=mysql
Case four
The problem of forgetting the database password
[[email protected] ~]# mysql -uroot -p
Enter password:
ERROR 1045 (28000): Access denied for user ‘root’@’localhost’ (using password: YES)
[[email protected] ~]# mysql -uroot -p
Enter password:
ERROR 1045 (28000): Access denied for user ‘root’@’localhost’ (using password: YES)
We may have just taken over someone else's MySQL database , And there is no perfect handover document .root Passwords can be lost or forgotten .
Solutions : No access to the database at the moment , So we have to consider whether we can skip the permission . Because in the database ,MySQL In the database user Tables record information about our users .
resolvent : start-up MySQL In the process of database , You can do this :
/usr/local/mysql/bin/mysqld_safe –defaults-file=/etc/my.cnf –skip-grant-tables &
This starts , You don't have to enter a password , Go straight into MySQL Database . Then change what you want to change root password .
update mysql.user set password=password(‘root123′) where user=’root’;
Case 5
truncate Delete data , Causes the auto clear auto increase ID, The front end returns an error not found
The emergence of this problem , Think about it truncate and delete The difference between the , Take a look at the experimental exercise :
First, create a table :
CREATE TABLE `t` (
`a` int(11) NOT NULL AUTO_INCREMENT,
`b` varchar(20) DEFAULT NULL,
PRIMARY KEY (`a`),
KEY `b` (`b`)
) ENGINE=InnoDB AUTO_INCREMENT=300 DEFAULT CHARSET=utf8
Insert three pieces of data :
mysql> insert into t (b) values (‘aa’);
Query OK, 1 row affected (0.00 sec)
mysql> insert into t (b) values (‘bb’);
Query OK, 1 row affected (0.00 sec)
mysql> insert into t (b) values (‘cc’);
Query OK, 1 row affected (0.00 sec)
mysql> select * from t;
+—–+——+
| a | b |
+—–+——+
| 300 | aa |
| 301 | bb |
| 302 | cc |
+—–+——+
3 rows in set (0.00 sec)
First use delete Delete the whole table information , Insert a new value .
Results found truncate Reset the auto increment initial value , Self increasing attribute from 1 It's starting to record . The current end uses the primary key id When making a query , It will report an error without this data .
Personal advice not to use truncate Delete the table , Although you can reclaim the table space , But it will involve the problem of self increasing attribute . These pits , We don't want to get in easily .
Case 6
Alibaba cloud MySQL Configuration file for
Alibaba cloud MySQL In the configuration file , One of the parameters you need to pay attention to :
lower_case_table_names = 0; By default .
lower_case_table_names = 1; Is it case sensitive .
If your lowercase table name cannot be found , Then you change the table name of the remote database to lowercase , vice versa . Be careful Mybatis Of Mapper All table names of the file should be modified accordingly .
Case seven
There will always be Chinese characters in the database
Some students often ask , Why does my database always have Chinese character disorder . I don't know what's wrong with a pile of Chinese characters ? When creating tables is written to the database , And insert Chinese , There will be such a problem . This error report will involve the problem of database character set .
Solutions : In the case of Chinese miscoding , Just remember what the teacher told you . Also know that in the current MySQL The character set encoding in the database is the default UTF8.
Treatment method :
Data terminal , That is, our tool for connecting to the database is set to utf8.
At the operating system level , Can pass cat /etc/sysconfig/i18n see , Also set it to utf8.
Database level , In the parameter file mysqld Next , Join in character-set-server=utf8.
Emoji Emoticons input MySQL Error in database :
Caused by: java.sql.SQLException: Incorrect string value: ‘ðð…’ for column ‘CONTENT’ at row 1
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4096)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4028)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2490)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2651)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2734)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)
at com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:1379)
Solutions : For the problem of expression insertion , It must be the character set .
processing method : We can do it directly in the parameter file , Join in :
vim /etc/my.cnf
[mysqld]
init-connect=’SET NAMES utf8mb4′
character-set-server=utf8mb4notes :utf8mb4 yes utf8 Superset .
Case eight
Use binlog_format=statement This format , Across the library operation , Causes data loss from the library , User access leads to error data messages
The current database binary log format is :binlog_format=statement
Set... In the main library binlog-do-db=mydb1( Sync only mydb1 This is a library ).
Execute... In the main library use mydb2;
insert into mydb1.t1 values (‘bb’); This statement is not synchronized to the slave Library .
But this way you can ;
use mydb1;
insert into mydb1.t1 values (‘bb’); Because it's done in the same library .
In the production environment, it is recommended to use binlog The format is row, And use it with caution binlog-do-db Parameters .
Case nine
MySQL Database connection timeout error
org.hibernate.util.JDBCExceptionReporter – SQL Error:0, SQLState: 08S01
org.hibernate.util.JDBCExceptionReporter – The last packet successfully received from the server was43200 milliseconds ago.The last packet sent successfully to the server was 43200 milliseconds ago, which is longer than the server configured value of ‘wait_timeout’. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection ‘autoReconnect=true’ to avoid this problem.
org.hibernate.event.def.AbstractFlushingEventListener – Could not synchronize database state with session
org.hibernate.exception.JDBCConnectionException: Could not execute JDBC batch update
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Connection.close() has already been called. Invalid operation in this state.
org.hibernate.util.JDBCExceptionReporter – SQL Error:0, SQLState: 08003
org.hibernate.util.JDBCExceptionReporter – No operations allowed after connection closed. Connection was implicitly closed due to underlying exception/error:
** BEGIN NESTED EXCEPTION **
Most do DBA Classmate , It may be told by developers , Your database reported this error , Let's see what the problem is .
This problem is affected by two parameters ,wait_timeout and interactive_timeout.
The default configuration time of data is 28800(8 Hours ) signify , Beyond that time ,MySQL Database in order to save resources , The connection will be disconnected on the database side ,MySQL The server side disconnected it , But our program doesn't make any judgment when it uses this connection again , So I hung up .
Solutions : First of all, we need to understand the characteristics of these two parameters , These two parameters must be set at the same time , And you have to make sure that the values are consistent .
We can increase this value appropriately ,8 Hours are too long , Not suitable for production environment . Because a connection doesn't work for a long time , It also takes up our connections , Will consume our system resources .
resolvent : It can be judged properly in the procedure , It is strongly recommended that the application logic be changed at the end of the operation to properly close the connection , Then set a more reasonable timeout Value ( Judge according to the business situation ).
Case 10
can’t open file (errno:24)
sometimes , The database is running well , All of a sudden, the error that the database file cannot be opened .
Solutions : First we need to check the database error log. Then judge whether the watch is damaged , It's still a matter of authority . It is also possible that the table cannot be accessed normally due to insufficient disk space ; The limitation of the operating system should also be concerned ; use perror Tools to see specific errors !
linux:/usr/local/mysql/bin # ./perror 24
OS error code 24: Too many open files
Maximum number of open files exceeded !ulimit -n The maximum number of open files to view the system is 65535, It's impossible to go beyond ! It must be that the maximum number of open files in the database exceeds the limit !
stay MySQL View the maximum number of open files limit command in :show variables like ‘open_files_limit’;
It is found that the value is too small , Change it to 2048, restart MySQL, The application is normal .
processing method :
repair table ;
chown mysql jurisdiction
Clean up the garbage data in the disk
边栏推荐
- 2022-2028 global protein confectionery industry research and trend analysis report
- Fabric of kubernetes CNI plug-in
- 浅谈Multus CNI
- Global and Chinese markets of thrombography hemostasis analyzer (TEG) 2022-2028: Research Report on technology, participants, trends, market size and share
- Write a mobile date selector component by yourself
- What are the advantages of automation?
- JDBC and MySQL database
- Explanation of for loop in golang
- Hands on deep learning (46) -- attention mechanism
- Exercise 8-10 output student grades (20 points)
猜你喜欢
Hands on deep learning (45) -- bundle search
2022-2028 global special starch industry research and trend analysis report
Daughter love: frequency spectrum analysis of a piece of music
mmclassification 标注文件生成
Hands on deep learning (37) -- cyclic neural network
2022-2028 global strain gauge pressure sensor industry research and trend analysis report
C # use gdi+ to add text with center rotation (arbitrary angle)
5g/4g wireless networking scheme for brand chain stores
PHP student achievement management system, the database uses mysql, including source code and database SQL files, with the login management function of students and teachers
Summary of reasons for web side automation test failure
随机推荐
C # use ffmpeg for audio transcoding
Four common methods of copying object attributes (summarize the highest efficiency)
Matlab tips (25) competitive neural network and SOM neural network
Hands on deep learning (45) -- bundle search
2022-2028 global elastic strain sensor industry research and trend analysis report
System. Currenttimemillis() and system Nanotime (), which is faster? Don't use it wrong!
智能网关助力提高工业数据采集和利用
查看CSDN个人资源下载明细
Nuxt reports an error: render function or template not defined in component: anonymous
智慧路灯杆水库区安全监测应用
Les différents modèles imbriqués de listview et Pageview avec les conseils de flutter
C language pointer interview question - the second bullet
Fatal error in golang: concurrent map writes
Deadlock in channel
Hands on deep learning (36) -- language model and data set
Hands on deep learning (46) -- attention mechanism
2022-2028 global small batch batch batch furnace industry research and trend analysis report
DR6018-CP01-wifi6-Qualcomm-IPQ6010-IPQ6018-FAMILY-2T2R-2.5G-ETH-port-CP01-802-11AX-MU-MIMO-OFDMA
Hands on deep learning (33) -- style transfer
Exercise 8-7 string sorting (20 points)