使用 JDBC 的 Java - 连接异常过多?

标签 java mysql jdbc

我试图从 url 中读取数据并存储在一个字符串中,当我将该字符串值存储在我的 sql 表中时,出现以下异常

Exception in thread "main" com.mysql.jdbc.exceptions.MySQLNonTransientConnectionException: Data source rejected establishment of connection,  message from server: "Too many connections"

如何删除这个异常

这是y代码

public class DownLoadData {

    Statement st = null;
    Connection connection = null;
    String driverName = "com.mysql.jdbc.Driver";
    String serverName = "localhost";
    String schema = "mandi";
    String url1 = "jdbc:mysql://" + serverName + "/" + schema;
    String username = "root";
    String password = "";

    public void DownloadCommodity() throws ClassNotFoundException, SQLException {
        int j = 0;
        String htmlTableText = null;
        System.setProperty("webdriver.chrome.driver", "C:\\Users\\SHAKTI\\Desktop\\JarFiles\\chromedriver_win32\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        String commodity = "Jo";
        String commo[] = {"Paddy", "Rice", "Jwar", "Barley", "Corn"
        };

        for (String com : commo) {
            String sDate = "27/03/2014";
            String url = "http://www.upmandiparishad.in/commodityWiseAll.aspx";
            driver.get(url);
            new Select(driver.findElement(By.id("ctl00_ContentPlaceHolder1_ddl_commodity"))).selectByVisibleText(com);
            driver.findElement(By.id("ctl00_ContentPlaceHolder1_txt_rate")).sendKeys(sDate);
            driver.findElement(By.id("ctl00_ContentPlaceHolder1_btn_show")).click();
            WebElement findElement = driver.findElement(By.id("ctl00_ContentPlaceHolder1_GridView1"));
            htmlTableText = findElement.getText();
      //  String html=find.getText();
            // do whatever you want now, This is raw table values.
            htmlTableText = htmlTableText.replace("S.No.DistrictMarketPrice", "");
            htmlTableText = htmlTableText.replaceAll("\\s(\\d+\\s[A-Z])", "\n$1");
            htmlTableText = htmlTableText.replaceAll("(?=(.*?[ ]){4,}).*?[\n\r]", "");
            htmlTableText = htmlTableText.replace("S.No. District Market Price", "");
            System.out.println(htmlTableText);
            String s[] = htmlTableText.split("");
            StringTokenizer str = new StringTokenizer(htmlTableText);
            while (str.hasMoreTokens()) // for(int i=0;i<s.length;i++)
            // if(str.hasMoreElements())
            {
                String no = str.nextElement().toString();

                String city = str.nextElement().toString();
                String mandi = str.nextElement().toString();
                String price = str.nextElement().toString();
                Class.forName(driverName);
                connection = DriverManager.getConnection(url1, username, password);
                PreparedStatement ps = connection.prepareStatement("insert into commoditydemo values(?,?,?,?,?,?)");
                ps.setString(1, no);
                ps.setString(2, city);
                ps.setString(3, mandi);
                ps.setString(4, price);
                ps.setString(5, com);
                ps.setString(6, "0");
                j = ps.executeUpdate();
                connection.close();

            }
        }
        driver.close();
        driver.quit();
        if (j == 1) {
            System.out.println("data inserted");
        } else {
            System.out.println("not inserted");
        }
    }

如何获得正确的输出?

提前致谢

最佳答案

我怀疑问题出在 while 循环的每次迭代 打开和关闭数据库连接。数据库需要大量清理工作才能关闭连接,您可能会创建关闭连接任务的积压,积压的速度比清除速度快。

最好在循环之前方法中打开一个连接一次,完成工作,然后在之后关闭连接环形。您可能需要围绕连接的使用进行 try-catch-finally 以确保它正确关闭。如果您使用的是 java 7,请使用 try-resource block 。

关于使用 JDBC 的 Java - 连接异常过多?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23488619/

相关文章:

jdbc - Kafka Connect JDBC OOM - 大数据量

java - FirebaseMessagingService onMessageReceived() 未执行

java - Java中如何知道Observer类发送的泛型对象?

java - 运行服务器时出现 BeanCreationException

php - PHP检查数组的IP,在SQL数据库?

java - 如何为 jdbc 模拟上下文数据源

java - JDBC:更新表的最佳方法?

java - 无法在 Eclipse 中使用 MigLayout,但可以在 Groovy Console 中使用

python - 如何在 Peewee 中选择二度 BackrefAccessor 的计数?

mysql - 优化这个mysql查询GROUP BY + ORDER BY + UNION ALL