: No operations allowed after statement closed.

时间:2025-04-09 09:00:31

 Mysql的数据库连接默认等待时限(wait_timeout)是8个小时,在该时限内如果没有使用该Connection(超过了这个时限),Connection就会被关闭。虽然该Connection已经被关闭,但Connection不为空。第一次调用时没有问题的,如果长时间没有使用该Connection,Connection会被Mysql关闭(但不为null)。此时调用该Connection时就会抛出异常: No operations allowed after connection  was implicitly closed by the driver.

  如果一个程序中使用一个共同的static的Connection时,这种问题就很容易出现。

查看Mysql的默认wait_timeout值(以下是我的Mysql中的配置)

show variables like '%timeout%';

+----------------------------+-------+

| Variable_name              | Value |

+----------------------------+-------+

| connect_timeout            | 10    |

| delayed_insert_timeout     | 300   |

| innodb_lock_wait_timeout   | 50    |

| innodb_rollback_on_timeout | OFF   |

| interactive_timeout        | 6000  |

| net_read_timeout           | 30    |

| net_write_timeout          | 60    |

| slave_net_timeout          | 3600  |

| table_lock_wait_timeout    | 50    |

| wait_timeout               | 6000  |

+----------------------------+-------+

10 rows in set (0.00 sec)

wait_timeout的值是6000秒。

解决方法:

1.修改Mysql的配置文件,添加一个属性,一旦Connection被自动关闭,便进行自动重连

2.在程序中进行判断,如hemowolf的方式。

3.使用更高级的数据库连接的jar,老的都会有这种问题。

4.不直接使用jdbc,改用Spring中的jdbcTemplate。