繁体   English   中英

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

[英]Java using JDBC - Too many connections Exception?

当我将字符串值存储在我的sql表中时,我试图从url读取数据并存储在字符串中,但我却收到以下异常消息

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

我如何删除此异常

这是你的代码

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循环的每次迭代中打开和关闭数据库连接。 数据库需要大量清理才能关闭连接,并且您可能正在创建关闭连接任务的积压订单,积压起来的速度比清除任务要快。

这将是最好的方法循环之前 ,一旦打开一个连接,做的工作,然后关闭循环的连接。 您可能需要围绕连接的使用进行最后尝试,以确保正确关闭连接。 如果您使用的是Java 7,请使用try-resource块。

您正在while循环中反复打开连接:

connection = DriverManager.getConnection(url1, username, password);

尝试外(前)放置连接的建立你的循环。 然后在循环完成后将其关闭。

试试这个代码:
我刚刚在while循环外初始化了连接。

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);
            connection = DriverManager.getConnection(url1, username, password);
            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);

                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");
        }
    }
  • 创建新连接是一件很慢的事情,因此,如果可以重复使用,请这样做。
  • 准备好的语句打算被重用。 阅读API文档以获取更多信息
  • 确保您的连接已关闭。 该界面扩展了Autoclosable,可与资源一起使用try

如果您想进行多次插入,那么更好的用户批处理并进行插入。

try{
String queryString = "insert into commoditydemo values(?,?,?,?,?,?)";
        PreparedStatement ps = con.prepareStatement(queryString);

        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);


                ps.setString(1, no);
                ps.setString(2, city);
                ps.setString(3, mandi);
                ps.setString(4, price);
                ps.setString(5, com);
                ps.setString(6, "0");
                ps.addBatch();
        }
        int[] rowsInsertedArray = ps.executeBatch();
        if(rowsInsertedArray.length != str.size()){throw new SQLException("Error in inserting users in commoditydemo");};
}
catch(SQLException e){
}
finally{
connection.close();
ps.close();
}

希望这会有所帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM