日期:2014-05-16  浏览次数:20761 次

MySQL 出现too many connections错误
     出现这个错误的原因是mysql服务器配置了指定数量的连接个数(mysql安装目录下my.ini【测试环境Windows XP】,  max_connections=10【默认为100,测试修改后的值】)。

   
     通过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  或 通过连接池。
【个人推荐】:连接池。