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

时间:2014-05-06 07:34:26

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

如何才能获得正确的输出?

提前致谢

5 个答案:

答案 0 :(得分:3)

我怀疑问题是打开和关闭while循环的每次迭代的数据库连接。数据库有相当大的清理工作来关闭连接,并且您可能正在创建积压的关闭连接任务,这些任务的建立速度比清除时快。

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

答案 1 :(得分:0)

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

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

尝试在您的循环外部(之前)建立连接。然后在循环结束后关闭它。

答案 2 :(得分:0)

试试这段代码:
我刚刚在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");
        }
    }

答案 3 :(得分:0)

  • 创建新连接是一件很慢的事情,因此如果您可以重复使用它,请执行此操作。
  • 准备好的陈述旨在重复使用。阅读API文档以获取更多信息
  • 确保您的连接已关闭。界面扩展为Autoclosable,使用try with resources

答案 4 :(得分:0)

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

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

希望这会有所帮助