有四个不同的数组字符串,我必须将所有数据插入数据库,但它仅将最后一个字符串数组存储到数据库中,并将第一,第二和第三个数组字符串的最后一个值存储。
public class Scrape {
private static final String url1 = "jdbc:mysql://localhost/Scraping_Data";
private static final String user = "root";
private static final String password = "root@123";
private String title="",rating="",price="",url="";
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public static void main(String[] args)throws IOException {
try
{
List<String> ar1 = new ArrayList<String>();
List<String> ar2 = new ArrayList<String>();
List<String> ar3 = new ArrayList<String>();
List<String> ar4 = new ArrayList<String>();
Class.forName("org.gjt.mm.mysql.Driver");
Connection con = DriverManager.getConnection(url1, user, password);
CallableStatement stmt = con.prepareCall("INSERT INTO datascrape(title, price, url, rating) VALUES(?, ?, ?, ?)");
Document doc = Jsoup.connect("-----------").get();
Elements temp=doc.select("div.productDisplay");
Scrape s=new Scrape();
int i=0;
for(Element itemlist:temp)
{
i++;
s.setTitle(itemlist.select("h4").text());
s.setPrice(itemlist.select("span.price").text());
s.setUrl(itemlist.select("a").attr("href"));
s.setRating(itemlist.select("div.ratings").text());
ar1.add(s.getTitle());
ar2.add(s.getPrice());
ar3.add(s.getUrl());
ar4.add(s.getRating());
}
String[] str1=ar1.toArray(new String[ar1.size()]);
String[] str2=ar2.toArray(new String[ar2.size()]);
String[] str3=ar3.toArray(new String[ar3.size()]);
String[] str4=ar4.toArray(new String[ar4.size()]);
for(String s1:str1) {
System.out.println("Title : "+s1);
stmt.setString(1, s1);
}
for(String s2:str2) {
System.out.println("Price : "+s2);
stmt.setString(2,s2);
}
for(String s3:str3)
{
System.out.println("URL : "+s3);
stmt.setString(3, s3);
}
for(String s4:str4) {
System.out.println("Rating : "+s4);
stmt.setString(4, s4);
stmt.execute();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
仅“等级”值插入数据库中。但是标题,价格和网址的最后一个值存储在列中
答案 0 :(得分:0)
您的概念有误。整个列表和数组都是不必要的。看看这个tutorial。
for(Element itemlist:temp)
{
stmt.setString(1, itemlist.select("h4").text());
stmt.setString(2, itemlist.select("span.price").text());
stmt.setString(3, itemlist.select("a").attr("href"));
stmt.setString(4, itemlist.select("div.ratings").text());
stmt.addBatch();
}
stmt.execute();