java.sql.SQLException: No operations allowed after statement closed.

java.sql.SQLException: No operations allowed after statement closed.


原因很简单:这里和数据库的连接Connection是一个Static的,程序共享这一个Connection。所以第一次对数据库操作没问题,当把Connection关闭后,第二次还想操作数据库时Connection肯定不存在了。

http://zhangsha1251.blog.163.com/blog/static/62624053201182111921783/

MyBatis连接MySQL出错:No operations allowed after connection closed

myBatis连接MySQL报异常:No operations allowed after connection closed.Connection was i

MyBatis连接MySQL出错:No operations allowed after connection closed

https://stackoverflow.com/questions/25883403/java-sql-sqlexception-no-operations-allowed-after-connection-closed

Well I found, the default time for closing connection if it has been inactive too long is 28800 seconds(8 hrs) for MYSQL (& not 34,247,052 milliseconds).

show global variables;

In MYSQL, I reset that value to 172800 seconds(48 hrs as per my requirement) using

set global wait_timeout=172800;

and it worked fine.

Thanks a lot for the help!

Mysql异常:MySQLNonTransientConnectionException: No operations allowed after statement closed

 Mysql的数据库连接默认等待时限(wait_timeout)是8个小时,在该时限内如果没有使用该Connection(超过了这个时限),Connection就会被关闭。虽然该Connection已经被关闭,但Connection不为空。第一次调用时没有问题的,如果长时间没有使用该Connection,Connection会被Mysql关闭(但不为null)。此时调用该Connection时就会抛出异常com.mysql.jdbc.exceptions.MySQLNonTransientConnectionException: No operations allowed after connection closed.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。

本文地址:https://www.jianshu.com/p/76ba02240eac

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值