简体   繁体   English

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

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

i am trying to read data from url and storing in a string when i am storing that string value in my my sql table i am getting following Exception 当我将字符串值存储在我的sql表中时,我试图从url读取数据并存储在字符串中,但我却收到以下异常消息

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

How can i remove this Exception 我如何删除此异常

Here is y code 这是你的代码

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

How can i get my correct output? 如何获得正确的输出?

Thanks in advance 提前致谢

I suspect that the problem is opening and closing the database connection every iteration of the while loop. 我怀疑问题是在while循环的每次迭代中打开和关闭数据库连接。 There is considerable clean up for the database to close a connection and you may be creating a backlog of close connection tasks that builds up faster than it is cleared. 数据库需要大量清理才能关闭连接,并且您可能正在创建关闭连接任务的积压订单,积压起来的速度比清除任务要快。

It would be better to open a connection once in the method before the loop, do the work, then close the connection after the loop. 这将是最好的方法循环之前 ,一旦打开一个连接,做的工作,然后关闭循环的连接。 You'll probably need a try-catch-finally around the use of the connection to ensure it is closed properly. 您可能需要围绕连接的使用进行最后尝试,以确保正确关闭连接。 If you are using java 7, use a try-resource block. 如果您使用的是Java 7,请使用try-resource块。

You are opening a connection repeatedly inside your while loop: 您正在while循环中反复打开连接:

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

Try to place the establishing of connection outside(before) your loops. 尝试外(前)放置连接的建立你的循环。 then close it after the loops are finished. 然后在循环完成后将其关闭。

Try this code : 试试这个代码:
I have just initialized connection outside while loop. 我刚刚在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");
        }
    }
  • Creating a new connection is a slow thing so if you can reuse it, do so. 创建新连接是一件很慢的事情,因此,如果可以重复使用,请这样做。
  • Prepared statements are intended to be reused. 准备好的语句打算被重用。 Read the API documentation for more info 阅读API文档以获取更多信息
  • Make sure your connection is closed. 确保您的连接已关闭。 The interface extends Autoclosable, use try with resources 该界面扩展了Autoclosable,可与资源一起使用try

If u want to do multiple inserts then better user batch and do insert. 如果您想进行多次插入,那么更好的用户批处理并进行插入。

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

hope this will be helpful 希望这会有所帮助

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

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