代码显示所有产品和价格,只需插入数据库 错误显示于 stmt.setstring(1, 标题) 任何人都可以解释这个错误 PreparedStatement 类型中的方法 setString(int, String) 不适用于参数 (int, Elements)
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Set;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
@SuppressWarnings("unused")
public class Main {
public static DB db = new DB();
public static void main(String[] args) throws SQLException, IOException {
db.runSql2("TRUNCATE Record;");
processPage("http://www.ebay.in/rpp/deals/electronics/electronics/mobiles/?_ipg=192");
}
public static void processPage(String URL) throws SQLException, IOException {
String url = "http://www.ebay.in/rpp/deals/electronics/electronics/mobiles/?_ipg=192";
Document doc = Jsoup.connect(url).timeout(1000 * 100).get();
Document doc1 = Jsoup.connect("http://www.ebay.in/rpp/deals/electronics/electronics/mobiles/?_ipg=192/")
.followRedirects(true).timeout(1000 * 100).get();
Elements title = doc.getElementsByClass("rttl");
System.out.println("title is: " + title);
Elements price = doc1.getElementsByClass("gl-cpr2");
System.out.println("Price is: " + price);
String sql = "INSERT INTO data " + "(Product Name) VALUES " + "(?);";
ResultSet rs = db.runSql(sql);
PreparedStatement stmt = db.conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stmt.setString(1, title);
stmt.execute();
String sql1 = "INSERT INTO data " + "(Product Name) VALUES " + "(?);";
ResultSet rs1 = db.runSql(sql);
PreparedStatement stmt1 = db.conn.prepareStatement(sql1, Statement.RETURN_GENERATED_KEYS);
stmt.setString(1, price);
stmt.execute();
}
}
最佳答案
您的数据类型不匹配。
调用 getElementsByClass() 可以获得许多结果。
setString() 方法需要一个字符串。
您可能希望循环遍历 Elements 对象(价格和标题)并一一处理结果。
以下是使用PreparedStatement批量插入的一些示例: Java: Insert multiple rows into MySQL with PreparedStatement
关于javascript - 我在这里编写了一个用于网络爬行的代码,我能够获取数据,但是准备好的语句不允许在 mysql Db 中插入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37523551/