我正在写一个网络爬虫,我遇到了一些麻烦。这是我正在尝试做的一些伪代码:
for every url in url-list {
urlid = NextURLID;
Insert urlid and url to their respective columns URL table
NextURLID++;
}
这是我到目前为止所做的:
void startCrawl() {
int NextURLID = 0;
int NextURLIDScanned = 0;
try
{
openConnection(); //Open the database
}
catch (SQLException | IOException e)
{
e.printStackTrace();
}
String url = "http://jsoup.org";
print("Fetching %s...", url);
Document doc = Jsoup.connect(url).get();
Elements links = doc.getElementsByTag("a");
for (Element link : links) {
urlID = NextURLID;
//Code to insert (urlid, url) to the URL table
NextURLID++;
}
}
正如您所看到的,我没有将url插入表中的代码。我认为会是这样的:
stat.executeUpdate("INSERT INTO urls VALUES ('"+urlID+"','"+url+"')");
但是如何使用每个循环迭代的新url覆盖urlID和url变量? 感谢
答案 0 :(得分:1)
在您的情况下,PreparementStatement更合适:
String insertURL = "INSERT INTO urls(urlID, url) VALUES (?, ?)";
PreparedStatement ps = dbConnection.prepareStatement(insertURL);
for (Element link : links) {
ps.setInt(1, NextURLID);
ps.setInt(2, link.attr("abs:href"));
ps.executeUpdate();
NextURLID++;
}
// ...