认识MySQL自身的状态和一些变量,状态可以帮助分析一些数据库方面的报错,同时帮助合理的设置一些对数据库访问的参数,这些都能在官方文档中找到
如下,查看timeout
,connect
相关的数据库变量
mysql> show variables like '%timeout%';
+-----------------------------+----------+
| Variable_name | Value |
+-----------------------------+----------+
| connect_timeout | 10 |
| delayed_insert_timeout | 300 |
| innodb_flush_log_at_timeout | 1 |
| innodb_lock_wait_timeout | 50 |
| innodb_rollback_on_timeout | OFF |
| interactive_timeout | 28800 |
| lock_wait_timeout | 31536000 |
| net_read_timeout | 30 |
| net_write_timeout | 60 |
| rpl_stop_slave_timeout | 31536000 |
| slave_net_timeout | 3600 |
| wait_timeout | 28800 |
+-----------------------------+----------+
12 rows in set (0.00 sec)
mysql>
mysql> show variables like '%connect%';
+-----------------------------------------------+-----------------+
| Variable_name | Value |
+-----------------------------------------------+-----------------+
| character_set_connection | utf8 |
| collation_connection | utf8_general_ci |
| connect_timeout | 10 |
| disconnect_on_expired_password | ON |
| init_connect | |
| max_connect_errors | 100 |
| max_connections | 151 |
| max_user_connections | 0 |
| performance_schema_session_connect_attrs_size | 512 |
+-----------------------------------------------+-----------------+
9 rows in set (0.00 sec)
mysql>
The number of seconds that the mysqld server waits for a connect packet before responding with Bad handshake.
默认10秒
mubi@mubideMacBook-Pro lib $ telnet 127.0.0.1 3306
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
J
5.6.40
x$HzQe'�asC0f2d"zdeMmysql_native_password
Connection closed by foreign host.
mubi@mubideMacBook-Pro lib $
限制每个用户的session连接个数(默认值为0,表示对用户无限制),例如max_user_connections=1 ,那么用户u1能连接的session数为1,如果还有用户u2,还是可以连接,但是连接数仍然为1;如果u1, u2再想连接,则会报错
参考:https://www.jb51.net/article/38933.htm
对整个服务器的连接限制,整个服务器只能同时开这么多个session
参考:https://www.jb51.net/article/51829.htm
交互式和非交互式链接的超时设置, 防止客户端长时间连接数据库,什么都不做处于sleep状态,强制关闭长时间的sleep连接。默认值为28800s(8h),一般会设置小一点
processlist
mysql> show full processlist;
+----+------+-----------------+------+---------+-------+-------+-----------------------+
| Id | User | Host | db | Command | Time | State | Info |
+----+------+-----------------+------+---------+-------+-------+-----------------------+
| 2 | root | localhost | test | Query | 0 | init | show full processlist |
| 8 | root | localhost:59270 | test | Sleep | 38068 | | NULL |
| 9 | root | localhost:59272 | test | Sleep | 37914 | | NULL |
| 10 | root | localhost:59288 | test | Sleep | 37914 | | NULL |
| 11 | root | localhost:59289 | test | Sleep | 708 | | NULL |
| 12 | root | localhost:59290 | test | Sleep | 650 | | NULL |
+----+------+-----------------+------+---------+-------+-------+-----------------------+
6 rows in set (0.00 sec)
mysql>
查看MySQL官方文档
The connection identifier. This is the same type of value displayed in the Id
column of the SHOW PROCESSLIST
statement, the PROCESSLIST_ID
column of the Performance Schema threads table, and returned by the CONNECTION_ID()
function.
The MySQL user who issued the statement. A value of system user
refers to a nonclient thread spawned by the server to handle tasks internally. This could be the I/O or SQL thread used on replication slaves or a delayed-row handler. For system user
, there is no host specified in the Host
column. unauthenticated user
refers to a thread that has become associated with a client connection but for which authentication of the client user has not yet been done. event_scheduler
refers to the thread that monitors scheduled events
The host name of the client issuing the statement (except for system user
, for which there is no host). The host name for TCP/IP connections is reported in host_name:client_port
format to make it easier to determine which client is doing what.
The default database, if one is selected; otherwise NULL
.
The type of command the thread is executing
The time in seconds that the thread has been in its current state. For a slave SQL thread, the value is the number of seconds between the timestamp of the last replicated event and the real time of the slave machine.
An action, event, or state that indicates what the thread is doing.
The statement the thread is executing, or NULL
if it is not executing any statement. The statement might be the one sent to the server, or an innermost statement if the statement executes other statements. For example, if a CALL
statement executes a stored procedure that is executing a SELECT
statement, the INFO
value shows the SELECT
statement.
state
mysql> show status like '%thread%';
+------------------------------------------+-------+
| Variable_name | Value |
+------------------------------------------+-------+
| Delayed_insert_threads | 0 |
| Performance_schema_thread_classes_lost | 0 |
| Performance_schema_thread_instances_lost | 0 |
| Slow_launch_threads | 0 |
| Threads_cached | 9 |
| Threads_connected | 1 |
| Threads_created | 711 |
| Threads_running | 1 |
+------------------------------------------+-------+
8 rows in set (0.00 sec)
mysql> show status like '%connect%';
+-----------------------------------------------+-------+
| Variable_name | Value |
+-----------------------------------------------+-------+
| Aborted_connects | 0 |
| Connection_errors_accept | 0 |
| Connection_errors_internal | 0 |
| Connection_errors_max_connections | 285 |
| Connection_errors_peer_address | 0 |
| Connection_errors_select | 0 |
| Connection_errors_tcpwrap | 0 |
| Connections | 1731 |
| Max_used_connections | 152 |
| Performance_schema_session_connect_attrs_lost | 0 |
| Ssl_client_connects | 0 |
| Ssl_connect_renegotiates | 0 |
| Ssl_finished_connects | 0 |
| Threads_connected | 1 |
+-----------------------------------------------+-------+
14 rows in set (0.00 sec)
mysql>
Aborted_clients
The number of connections that were aborted because the client died without closing the connection properly.
Aborted_connects
The number of failed attempts to connect to the MySQL server.
Threads_connected
The number of currently open connections.
Threads_created
The number of threads created to handle connections. If Threads_created
is big, you may want to increase the thread_cache_size
value. The cache miss rate can be calculated as Threads_created/Connections
.
Threads_running
The number of threads that are not sleeping.
Threads_cached
The number of threads in the thread cache.
This variable is not meaningful in the embedded server (libmysqld) and as of MySQL 5.7.2 is no longer visible within the embedded server.
mubi@mubideMacBook-Pro ~ $ mysql -uroot -p
Enter password:
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
mysql> show status like '%Abort%';
+------------------+-------+
| Variable_name | Value |
+------------------+-------+
| Aborted_clients | 208 |
| Aborted_connects | 0 |
+------------------+-------+
2 rows in set (0.00 sec)
mysql> show status like '%Abort%';
+------------------+-------+
| Variable_name | Value |
+------------------+-------+
| Aborted_clients | 208 |
| Aborted_connects | 1 |
+------------------+-------+
2 rows in set (0.00 sec)
mysql>
mubi@mubideMacBook-Pro ~ $ mysql -h 127.0.0.1 -P 3306 -u aaa -p111
Warning: Using a password on the command line interface can be insecure.
ERROR 1045 (28000): Access denied for user 'aaa'@'localhost' (using password: YES)
mubi@mubideMacBook-Pro ~ $ curl 127.0.0.1:3306
5.6.40.Xk5ahiVQ��tti4e!o2GO9kmysql_native_password!��#08S01Got packets out of ordermubi@mubideMacBook-Pro ~ $
connect_timeout
控制(mysql默认是10s,基本上,除非网络环境极端不好,一般不会超时。表示客户端没有正确的关闭连接,而被终止的连接数
# -*- coding:utf-8 -*-
import pymysql
class Database(object):
def __init__(self):
self.dbhost = '127.0.0.1'
self.port = 3306
self.dbuser = 'root'
self.dbpass = ''
self.dbname = 'test'
# DB_URI = 'mysql://' + dbuser + ':' + dbpass + '@' + dbhost + '/' + dbname
self.conn = None
def connect(self):
self.conn = pymysql.connect(host=self.dbhost,
port=self.port,
user=self.dbuser,
password=self.dbpass,
database=self.dbname)
def close(self):
try:
self.conn.close()
except:
raise ValueError('conn close exception')
def query(self, sql):
if self.db:
cursor = self.db.cursor()
cursor.execute(sql)
else:
raise ValueError('DB not connected')
def handle_query():
db = Database()
db.connect()
cur = db.conn.cursor()
sql = "select id, sno, name from t_user"
cur.execute(sql)
rows = cur.fetchall()
print(rows)
cur.close()
# db.close()
if __name__ == '__main__':
handle_query()
set global wait_timeout=5;
# -*- coding:utf-8 -*-
import pymysql
import time
class Database(object):
def __init__(self):
self.dbhost = '127.0.0.1'
self.port = 3306
self.dbuser = 'root'
self.dbpass = ''
self.dbname = 'test'
# DB_URI = 'mysql://' + dbuser + ':' + dbpass + '@' + dbhost + '/' + dbname
self.conn = None
def connect(self):
self.conn = pymysql.connect(host=self.dbhost,
port=self.port,
user=self.dbuser,
password=self.dbpass,
database=self.dbname)
def close(self):
try:
self.conn.close()
except:
raise ValueError('conn close exception')
def query(self, sql):
if self.db:
cursor = self.db.cursor()
cursor.execute(sql)
else:
raise ValueError('DB not connected')
def handle_query():
db = Database()
db.connect()
# 可以睡眠超过`wait_timeout`
print("sleep 6 seconds")
time.sleep(6)
cur = db.conn.cursor()
sql = "select id, sno, name from t_user"
cur.execute(sql)
rows = cur.fetchall()
print(rows)
cur.close()
db.close()
if __name__ == '__main__':
handle_query()
https://github.com/doctording/MyTodos/blob/master/code/README.md
部分转自:
https://www.jb51.net/article/66868.htm
https://blog.csdn.net/u011537073/article/details/73522408
https://blog.csdn.net/u012326462/article/details/80872985