使用Statement获取结果集

Statement sta = con.createStatement();
ResultSet rst = sta.executeQuery("select * from book");

使用PreparedStatement获取结果集

PreparedStatement pst = con.preparedStatement("select * from book");
ResultSet rst = pst.executeQuery();

这两个选项可以正确获取结果集。

错误选项分析

以下选项存在错误:

  1. Statementsta=con.createStatement("select*frombook"); - 创建Statement对象时不应该传入SQL语句。
  2. PreparedStatementpst=con.preparedStatement("select*frombook");ResultSetrst=pst.executeQuery(select*frombook"); - 在执行查询时,应该使用占位符而不是直接传入SQL语句。
  3. PreparedStatementpst=con.preparedStatement("select*frombook");ResultSetrst=pst.executeQuery(); - 在执行查询时,应该使用占位符而不是直接传入SQL语句。

结论

使用Statement或PreparedStatement获取结果集时,需要根据实际情况选择合适的方法,并确保代码语法正确。使用PreparedStatement可以提高代码可读性和安全性。

Java JDBC: 如何正确获取结果集?

原文地址: http://www.cveoy.top/t/topic/zvC 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录