通过DriverManager.getConnection(url, username, pwd)获取连接数大于mysql中配置的max_connections数就会报【mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Data source rejected establishment of connection, message from server: "Too many connections"】
报错的测试代码:
for (int i = 1; i <= 20; i++) { new Thread(new Runnable() { public void run() { Connection conn = null; try { conn = DBUtils.getConnection(); synchronized (counter) { System.out.print(Thread.currentThread().getName()); System.out.print(" counter = " + counter++ + " conn = " + conn); System.out.println(); conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } }).start(); }
解决方案:修改my.ini配置文件中的连接数max_connections 或 通过连接池。
【个人推荐】:连接池。