我正在尝试从网站中提取值并在我的数据库中插入值,当我要在我的数据库中插入数据时我正在获取此异常
异常是:线程中的异常" main" java.util.NoSuchElementException
这是我的代码
public class ScrapCom {
Statement st = null;
Connection cn = null;
public static void main(String args[]) throws InterruptedException, ClassNotFoundException, SQLException {
int j = 0;
WebDriver driver = new HtmlUnitDriver(BrowserVersion.getDefault());
String sDate = "27/03/2014";
String url = "http://www.upmandiparishad.in/commodityWiseAll.aspx";
driver.get(url);
Thread.sleep(5000);
new Select(driver.findElement(By.id("ctl00_ContentPlaceHolder1_ddl_commodity"))).selectByVisibleText("Jo");
driver.findElement(By.id("ctl00_ContentPlaceHolder1_txt_rate")).sendKeys(sDate);
Thread.sleep(3000);
driver.findElement(By.id("ctl00_ContentPlaceHolder1_btn_show")).click();
Thread.sleep(5000);
WebElement findElement = driver.findElement(By.id("ctl00_ContentPlaceHolder1_GridView1"));
String htmlTableText = findElement.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]", "");
System.out.println(htmlTableText);
StringTokenizer str = new StringTokenizer(htmlTableText);
while (str.hasMoreElements()) {
for (int i = 0; i < 4; i++) {
String no = str.nextElement().toString();
String city = str.nextElement().toString();
String mandi = str.nextElement().toString();
String price = str.nextElement().toString();
Class.forName("com.mysql.jdbc.Driver");
Connection cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mandi", "root", "");
//insert them into the database
PreparedStatement ps = cn.prepareStatement("insert into commoditywise values(?,?,?,?)");
ps.setString(1, no);
ps.setString(2, city);
ps.setString(3, mandi);
ps.setString(4, price);
j = ps.executeUpdate();
cn.close();
}
}
if (j == 1) {
System.out.println("data inserted");
} else {
System.out.println("not inserted");
}
driver.close();
driver.quit();
}
}
更新了例外
Exception in thread "main" java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(StringTokenizer.java:349)
at java.util.StringTokenizer.nextElement(StringTokenizer.java:407)
at Getdata1.main(Getdata1.java:48)
Java Result: 1
我在这里缺少什么?
如何删除此异常
提前致谢
答案 0 :(得分:1)
我猜你的问题不是数据库插入。如果下一个元素可用,则您使用StringTokenizer.nextElement()
而不使用testig。
while (str.hasMoreElements()) {
for (int i = 0; i < 4; i++) {
String no = str.nextElement().toString();
String city = str.nextElement().toString();
String mandi = str.nextElement().toString();
String price = str.nextElement().toString();
如果您连续多次进行nextElement()
次调用,首先应使用StringTokenizer.countTokens()
检查预期的令牌数是否可用
public int countTokens()
计算此令牌化程序的nextToken方法可以被调用的次数&gt;在它生成异常之前。目前的立场没有提前。
返回: 使用当前分隔符集保留在字符串中的标记数。 也可以看看: 的nextToken()