java resultset execute 没有查询到_Java ResultSet如何检查是否有任何结果

这是正确的,最初ResultSet的光标指向第一行之前,如果第一次调用next()返回false那么在ResultSet没有数据。

如果你使用这个方法,你可能不得不立即调用beforeFirst()来重置它,因为它已经把自己定位在第一行之后了。

但是,应该指出的是, Seifer的答案是对这个问题更为优雅的解决scheme。

假设你正在处理一个新返回的ResultSet它的游标指向第一行之前,更简单的方法是调用isBeforeFirst() 。 这避免了如果要读取数据就必须回溯。

如文档中所述,如果游标不在第一个logging之前,或者ResultSet中没有行,则返回false。

if (!resultSet.isBeforeFirst() ) { System.out.println("No data"); }

你总是可以做的下一个前面,只是做一个后循环检查

if (!resultSet.next() ) { System.out.println("no data"); } else { do { //statement(s) } while (resultSet.next()); }

你通常会做这样的事情:

while ( resultSet.next() ) { // Read the next item resultSet.getString("columnName"); }

如果你想报告一个空集,添加一个variables计数读取的项目。 如果您只需要阅读单个项目,那么您的代码就足够了。

最好使用ResultSet.next()以及do {…} while()语法。

“检查任何结果”调用ResultSet.next()将光标移动到第一行,所以使用do {…} while()语法来处理该行,同时继续处理循环返回的剩余行。

这样你可以检查任何结果,同时也处理返回的结果。

if(resultSet.next()) { // Checks for any results and moves cursor to first row, do { // Use 'do...while' to process the first row, while continuing to process remaining rows } while (resultSet.next()); }

根据最可行的答案,build议使用“isBeforeFirst()”。 如果您没有“仅前向型”,那不是最好的解决scheme 。

有一个叫“ .first() ”的方法。 获得完全相同的结果不那么矫枉过正。 你检查你的“结果集”中是否有东西,并且不要提前你的光标。

该文档指出:“(…)如果结果集中没有行,则为false”。

if(rs.first()){ //do stuff }

你也可以直接调用isBeforeFirst()来testing是否有任何返回的行没有前进光标,然后正常进行。 – SnakeDoc 9年9月2日在19:00

但是,“isBeforeFirst()”和“first()”是有区别的。 如果在types为“forward only”的结果集上完成,则首先会生成一个exception。

比较两个throw部分: http : //docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#isBeforeFirst() http://docs.oracle.com/javase/7/docs /api/java/sql/ResultSet.html#first()

好的,基本上这意味着只要你有一个“只有前进”的types,你应该使用“isBeforeFirst”。 否则,使用“first()”就不那么矫枉过正了。

如果你想查看结果集中是否有任何行是的,这将工作。

请注意, next()总是移动到下一行,因此如果您计划从结果集中读取数据,则需要考虑这一点。

ResultSet的常用用法(简单阅读时)是:

while (resultSet.next()) { ... read from the row here ... }

如果你调用next()一次已经检查结果集是否为空,那么显然不能正确工作,所以要小心。 虽然有“备份”方法,但不支持所有types的结果集。

要完全确定结果集是空的还是不pipe光标位置,我会做这样的事情:

public static boolean isMyResultSetEmpty(ResultSet rs) throws SQLException { return (!rs.isBeforeFirst() && rs.getRow() == 0); }

如果ResultSet为空,则此函数将返回true,否则返回false,如果该ResultSet已closures/未初始化,则返回SQLException。

if (!resultSet.isAfterLast() ) { System.out.println("No data"); }

isAfterLast()对于空的结果集也返回false,但是由于光标位于第一行之前,所以这个方法似乎更清晰。

我相信这是一个实用而易读的作品。

if (res.next()) { do { // successfully in. do the right things. } while (res.next()); } else { // no results back. warn the user. }

if(reset.first) { } else { system.out.println("No raw or reset is empty"); }

因为如果ResultSet没有raw,那么reset.first返回false。

最好的办法是检查第一行,以便当你打算获取数据时,可以避免跳过一行的错误。 就像:if(!resultSet.first()){System.out.println(“no data”); }

通过使用resultSet.next(),你可以很容易地得到结果,无论resultSet是否包含任何值

ResultSet resultSet = preparedStatement.executeQuery(); if(resultSet.next()) //resultSet contain some values else // empty resultSet

ResultSet rs = rs.executeQuery(); if(rs.next()) { rs = rs.executeQuery(); while(rs.next()) { //do code part } } else { //else if no result set }

因为当我们调用if(rs.next()){....}第一行将被执行,并且在它后面while(rs.next()){....}我们会从下一行得到结果。 所以我认为if是更好的select,重新执行查询里面。

ResultSet result = stmt.executeQuery(sqlQuery); if (!result.next()) status = "ERROR"; else status = "SUCCESS";

我创build了以下方法来检查ResultSet是否为空。

public static boolean resultSetIsEmpty(ResultSet rs){ try { // We point the last row rs.last(); int rsRows=rs.getRow(); // get last row number if (rsRows == 0) { return true; } // It is necessary to back to top the pointer, so we can see all rows in our ResultSet object. rs.beforeFirst(); return false; }catch(SQLException ex){ return true; } }

有以下的考虑是非常重要的:

CallableStatement对象必须设置为让ResultSet对象在最后走到顶部。

TYPE_SCROLL_SENSITIVE :ResultSet对象可以在最后移动并返回顶部。 进一步可以赶上最后的变化

CONCUR_READ_ONLY :我们可以读取ResultSet对象的数据,但不能更新。

CallableStatement proc = dbconex.prepareCall(select, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);

你可以做这样的事情

boolean found = false; while ( resultSet.next() ) { found = true; resultSet.getString("column_name"); } if (!found) System.out.println("No Data");

我一直在试图设置当前行到第一个索引(处理主键)。 我会build议

if(rs.absolute(1)){ System.out.println("We have data"); } else { System.out.println("No data"); }

当填充ResultSet时,它指向第一行之前。 将其设置为第一行(由rs.absolute(1)指示)时,将返回true表示已成功放置在第1行,如果该行不存在,则返回false。 我们可以推断这一点

for(int i=1; rs.absolute(i); i++){ //Code }

将当前行设置为位置i,如果该行不存在,将会失败。 这只是一个替代方法

while(rs.next()){ //Code }

我认为检查结果集最简单的方法是通过CollectionUtils包org.apache.commons.collections.CollectionUtils

if(CollectionUtils.isNotEmpty(resultList)){ /** * do some stuff */ }

这将检查null以及空的结果集条件。

有关更多详细信息,请参阅以下文档。 CollectionUtils

为什么不使用rs.getRow()?

int getRow() throws SQLException Retrieves the current row number. The first row is number 1, the second number 2, and so on. Note:Support for the getRow method is optional for ResultSets with a result set type of TYPE_FORWARD_ONLY Returns: the current row number; 0 if there is no current row Throws: SQLException - if a database access error occurs or this method is called on a closed result set SQLFeatureNotSupportedException - if the JDBC driver does not support this method Since: 1.2

对我来说,检查“if(rs.getRow()!= 0)”似乎工作得很好。

最初,结果集对象(rs)指向BFR(在第一条logging之前)。 一旦我们使用rs.next(),光标指向第一个logging,rs持有“true”。 使用while循环可以打印表格的所有logging。 在所有的logging被检索后,光标移动到ALR(最后一个logging之后),它将被设置为空。 让我们考虑一下表中有两条logging。

if(rs.next()==false){ // there are no records found } while (rs.next()==true){ // print all the records of the table }

简而言之,我们也可以把这个条件写成while(rs.next())。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
/* * Copyright (c) 2000 David Flanagan. All rights reserved. * This code is from the book Java Examples in a Nutshell, 2nd Edition. * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied. * You may study, use, and modify it for any non-commercial purpose. * You may distribute it non-commercially as long as you retain this notice. * For a commercial use license, or to purchase the book (recommended), * visit http://www.davidflanagan.com/javaexamples2. */ package com.hexiang.examples.servlet; import javax.servlet.*; import javax.servlet.http.*; import java.sql.*; import java.io.*; /** * This class demonstrates how JDBC can be used within a servlet. It uses * initialization parameters (which come from the web.xml configuration file) * to create a single JDBC database connection, which is shared by all clients * of the servlet. ***/ public class Query extends HttpServlet { private static final long serialVersionUID = -5616899811848789885L; Connection db; // This is the shared JDBC database connection public void init() throws ServletException { // Read initialization parameters from the web.xml file ServletConfig config = getServletConfig(); String driverClassName = config.getInitParameter("driverClassName"); String url = config.getInitParameter("url"); String username = config.getInitParameter("username"); String password = config.getInitParameter("password"); // Use those init params to establish a connection to the database // If anything goes wrong, log it, wrap the exception and re-throw it try { Class.forName(driverClassName); db = DriverManager.getConnection(url, username, password); } catch (Exception e) { log("Can't create DB connection", e); throw new ServletException("Query: can't initialize: " + e.getMessage(), e); } } /** Close the database connection when the servlet is unloaded */ public void destroy() { try { db.close(); } // Try to close the connection catch (SQLException e) {} // Ignore errors; at least we tried! } public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); // We're outputting HTML PrintWriter out = response.getWriter(); // Where to output it to // Output document header and a form for entering SQL queries // When the form is submitted, this servlet is reloaded out.println("<head><title>DB Query</title></head>\n" + "<body bgcolor=white><h1>DB Query</h1>\n" + "<form><b>Query: </b><input name='q'>" + "<input type=submit></form>"); // See if a query was specified in this request. String query = request.getParameter("q"); if (query != null) { // display the query text as a page heading out.println("<h1>" + query + "</h1>"); // Now try to execute the query and display the results in a table Statement statement = null; // An object to execute the query try { // Create a statement to use statement = db.createStatement(); // Use it to execute the specified query, and get result set ResultSet results = statement.executeQuery(query); // Ask for extra information about the results ResultSetMetaData metadata = results.getMetaData(); // How many columns are there in the results? int numcols = metadata.getColumnCount(); // Begin a table, and output a header row of column names out.println("<table border=2><tr>"); for(int i = 0; i < numcols; i++) out.print("<th>" + metadata.getColumnLabel(i+1) + "</th>"); out.println("</tr>"); // Now loop through the "rows" of the result set while(results.next()) { // For each row, display the the values for each column out.print("<tr>"); for(int i = 0; i < numcols; i++) out.print("<td>" + results.getObject(i+1) + "</td>"); out.println("</tr>"); } out.println("</table>"); // end the table } catch (SQLException e) { // If anything goes wrong (usually a SQL error) display the // error to the user so they can correct it. out.println("SQL Error: " + e.getMessage()); } finally { // Whatever happens, always close the Statement object try { statement.close(); } catch(Exception e) {} } } // Now, display the number of hits on this page by invoking the // Counter servlet and including its output in this page. // This is done with a RequestDispatcher object. RequestDispatcher dispatcher = request.getRequestDispatcher("/servlet/counter"); if (dispatcher != null) { out.println("<br>Page hits:"); // Add a request attribute that tells the servlet what to count. // Use the attribute name defined by the Counter servlet, and // use the name of this class as a unique counter name. request.setAttribute(Counter.ATTRIBUTE_NAME,Query.class.getName()); // Tell the dispatcher to invoke its servlet and include the output dispatcher.include(request, response); } // Finally, end the HTML output out.println("</body>"); } }
此工具我不再更新,里面大多数方法我迁移到了hutool工具包中,而其中一些不常用的功能被遗弃,项目暂留做为以后参考。 common-tools 一、数据库工具类 1、com.baijob.commonTools.db.ds C3p0Ds 和 DruidDs分别是两种连接池的实现,依赖于数据库配置文件,配置文件的样例参考config/db-example.setting 使用时将db-example.setting复制于${classpath}/config/db.setting,按照配置文件中的说明替换相应值 如果使用Druid,则需参考druid-example.setting创建${classpath}/config/druid.setting文件,详情请参考官方文档 使用C3P0则需要参考c3p0-config-example.xml创建${classpath}/c3p0-config.xml来调节C3P0参数 此时即可调用C3p0Ds.getDataSource()或DruidDs.getDataSource()方法获得默认的数据源 如果要自定义数据库配置文件的参数,请调用相应的init(),传入相关参数 注:Setting对象请参考与之对应的章节 2、com.baijob.commonTools.db.DbUtil 数据库工具类,提供了关闭方法:关闭可以传入多个参数,关闭的顺序是按照参数的顺序来的,用于一次性关闭Connnection、Statement、ResultSet等 newSqlRunner方法用于快速新建一个SqlRunner(此类介绍参考下问) 3、com.baijob.commonTools.db.DsSetting,用于读取db.setting文件辅助类,内部使用 4、com.baijob.commonTools.db.SqlRunner类参考Apache的DbUtils工具包,封装了常用的增删改查方法,与com.baijob.commonTools.db.RsHandler配合使用 com.baijob.commonTools.db.RsHandler接口与Apache的DbUtils的ResultSetHandler等价,抽象结果集处理。 二、邮件工具类 1、com.baijob.commonTools.mail.MailAccount 邮件账户类。 可以调用MailAccount(String accountSettingFileBaseClassLoader)读取相对路径的Setting文件,配置参考mailAccount-example.setting 2、com.baijob.commonTools.mail.MailUtil邮件发送工具类,方法请参考注释 此工具类依赖javax.mail,请参考pom.xml添加依赖或手动下载 三、网络相关工具类 1、com.baijob.commonTools.net.AccessControl访问控制,基于配置文件,可以设定IP白名单或黑名单,可以通过配置文件实现简单的账户验证。 配置文件请参考access-example.xml 2、com.baijob.commonTools.net.Connector 连接对象实体类,有host、端口、用户名、密码等属性 3、com.baijob.commonTools.net.HtmlUtil HTML工具类,暂时只提供特殊字符转义 4、com.baijob.commonTools.net.SocketUtil socket工具类。 isUsableLocalPort() 检测本地某个端口是否可用(可用是指没有被其他程序占用) isValidPort()是否是符合规范的端口号 longToIpv4()将long转换为ipv4地址,反方法是ipv4ToLong() netCat()简易的数据发送方法 5、com.baijob.commonTools.net.SSHUtil SSH相关工具类 getSession()获得一个SSH会话 bindPort()将远程主机的端口映射到本地某个端口 6、com.baijob.commonTools.net.URLUtil 将相对、绝对路径转换为URL对象,用于网络或文件流的读写,Setting的配置依赖此工具包 四、线程相关工具类 1、com.baijob.commonTools.thread.BaseRunnable 此类实现了Runnable接口,扩展了功能。 增加名称、ID,调用次数和时间统计、线程停止接口等,并且在线程运行时,不允许此线程第二次启动。 2、com.baijob.commonTools.thread.Executor 线程池工具类 调用静态方法execute()启动线程,此线程在公共的线程池中执行 若想自定义线程池大小或独立控制,可调用newExecutor()实例化一个线程池 excAsync()执行一个异步方法 3、com.baijob.commonTools.thread.SyncQueue 阻塞队列,简化了JDK的BlockingQueue
import java.sql.*; import jdbc.DBManager; import jdbc.DBManagerTest; /** * <p>Title: </p> * <p>Description: </p> * <p>Copyright: Copyright (c) 2002</p> * <p>Company: </p> * @author * @version 1.0 */ /** * DBManager示例程序 */ public class Test { public Test() { } public static void main(String[] args) { DBManagerTest DBManagerTest1 = new DBManagerTest(); DBManager db_manager = new DBManager(); ResultSet result = null; // 数据库查询结果 try { db_manager.connect("rcms"); // 建表 db_manager .execute("create table table22 (c1 varchar(32) not null,c2 varchar(21))"); } catch (SQLException x) { x.printStackTrace(); try { db_manager.disconnect(); } catch (SQLException e) { // TODO 自动生成 catch 块 e.printStackTrace(); } System.err.print("数据库操作失败!"); } try { // 表更新操作,包括insert,update,delete db_manager .executeUpdate("insert into table22 (c1,c2) values('workflow1','engine1')"); db_manager .executeUpdate("insert into table22 (c1,c2) values('workflow2','engine2')"); db_manager .executeUpdate("insert into table22 (c1,c2) values('workflow3','engine3')"); db_manager .executeUpdate("insert into table22 (c1,c2) values('workflow4','engine4')"); db_manager.beginTransaction(); // for(int i=1500;i<2000;i++){ //// db_manager.executeUpdate("insert into T_USER (USER_ID, USER_NAME, ORG_ID, PASSWD, OLD_PASSWD, STATION, CREAT_DATE, CREAT_TIME, ALTER_DATE, ALTER_TIME, DEL_DATE, TEL, EMAIL, STATUS, SEX, ACADEMIC, CERTI_TYPE, CERTI, FAX, ADRESS, POSTCODE, BAK1, BAK2, BAK3, BAK4, BAK5)values ('test00"+i+"', 'test00"+i+"', '0001 ', 'FF5E61835C355E755EEF9321 ', 'A43B59E342F86CEE5EEF9321 ', '0 ', '20071201', '101010', null, null, null, null, null, '1', null, null, null, null, null, null, null, null, null, null, null, null)"); // db_manager.executeUpdate("insert into T_USER_ROLE values('test00"+i+"','sys_admin','')"); // if(i%300==0)db_manager.commitTransaction(); // } } catch (SQLException x) { x.printStackTrace(); try { db_manager.disconnect(); } catch (SQLException e) { // TODO 自动生成 catch 块 e.printStackTrace(); } System.err.print("数据库操作失败!"); } try { // 表查询操作,返回结果集存在DBResult类中,DBResult中的数据库查询结果已与数据库断开连接了, // 不能动态更新,注意在并发操作中应重新执行表查询操作 result = db_manager.executeQuery("select * from table22"); } catch (SQLException x) { x.printStackTrace(); try { db_manager.disconnect(); } catch (SQLException e) { // TODO 自动生成 catch 块 e.printStackTrace(); } System.err.print("数据库操作失败!"); } // int rows = result.getRows(); //返回的记录数 try { while (result.next()) { String s = result.getString("c1");// 取第4条记录c1的字段 System.out.println(s); s = result.getString("c2"); System.out.println(s); } } catch (SQLException e) { // TODO 自动生成 catch 块 e.printStackTrace(); } } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值