java resultset execute 没有查询到_关于jdbc:Java ResultSet如何检查是否有任何结果

结果集没有hasNext的方法。 我想检查resultSet是否有任何值

这是正确的方法吗

if (!resultSet.next() ) {

System.out.println("no data");

}

对于像我这样的未来读者:那些帮助我的答案来自Felype和Dermot Doherty

假设您正在使用一个新返回的ResultSet,其光标指向第一行之前,则更简单的检查方法是调用isBeforeFirst()。如果要读取数据,这避免了必须回溯。

如文档中所述,如果光标不在第一条记录之前,或者ResultSet中没有行,则返回false。

if (!resultSet.isBeforeFirst() ) {

System.out.println("No data");

}

谢谢,是的,我知道,但是我遇到了同样的问题,对前进查看然后向后阅读的外观感到不满意。我认为这种简单的解决方案也会使处于相同情况的其他人受益。

注意,至少对于DB2,结果集必须是"可滚动"类型。您可以在创建要执行的语句时进行设置。

Felypes下面的答案比较完整

来自Oracle文档:注意:对于结果集类型为TYPE_FORWARD_ONLY的ResultSet,对isBeforeFirst方法的支持是可选的

没错,最初ResultSet的光标指向第一行之前,如果第一次调用next()返回false,则ResultSet中没有数据。

如果使用此方法,则可能必须在调用beforeFirst()后立即将其重置,因为它现在已经位于第一行之后。

但是,应该注意的是,Seifer在下面的回答是对该问题的更优雅的解决方案。

但是请记住,如果有/ are /行,那么在测试之后,您将指向第一行。因此,请确保您不会意外跳过行。

光标(指针)指向第一行的好点

@MatthewFlaschen,您好,为了解决跳过第一行的问题,我使用了do {...} while(rs.next);

您也可以只调用isBeforeFirst()来测试是否有返回的行而不前进光标,然后正常进行。

您总是可以预先做下一个,然后进行循环后检查

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");

}

如果要报告一个空集,请添加一个变量,以计算读取的项目。如果您只需要阅读一个项目,那么您的代码就足够了。

为了完全确定结果集为空还是与光标位置无关,我将执行以下操作:

public static boolean isMyResultSetEmpty(ResultSet rs) throws SQLException {

return (!rs.isBeforeFirst() && rs.getRow() == 0);

}

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

最好将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());

}

根据最可行的答案,建议是使用" isBeforeFirst()"。如果您没有"仅转发类型",那不是最佳解决方案。

有一个称为" .first()"的方法。获得完全相同的结果就不会太矫kill过正。您检查"结果集"中是否有内容,并且不要使光标前进。

文档中指出:"(...)如果结果集中没有行,则为false"。

if(rs.first()){

//do stuff

}

You can also just call isBeforeFirst() to test if there are any rows returned without advancing the cursor, then proceed normally. – SnakeDoc Sep 2 '14 at 19:00

但是," isBeforeFirst()"和" first()"之间是有区别的。如果对"仅转发"类型的结果集进行处理,则首先会生成异常。

比较两个抛出部分:

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()

好的,基本上,这意味着只要您具有"仅转发"类型,就应该使用" isBeforeFirst"。否则,使用" first()"不会造成太大的伤害。

如何获得完全相同的结果呢?在我看来,first()的目的是将光标移动到第一行(如果它还不存在的话)(如果成功则返回true)。 isBeforeFirst仅是纯诊断功能,似乎更适合作者的目的。另外,first()的措词方式是,只要它的"在有效行上",它就返回true……这很奇怪,就像人们认为它在"在第一行"上那样。对我来说,除非您的光标已经前进并且希望将其重新开始,否则在这种情况下我看不到使用first()的优势。

如果您想查看结果集中是否有任何行,那将起作用。

请注意,next()始终移至下一行,因此,如果您打算从结果集中进行任何读取,则需要考虑到这一点。

ResultSet的常规用法(当简单阅读时)为:

while (resultSet.next())

{

... read from the row here ...

}

如果您已经调用一次next()来检查结果集是否为空,则显然不能正常工作,因此请当心。尽管有用于"备份"的方法,但并非所有类型的结果集都支持它们。

我相信这是一本实用且容易阅读的文章。

if (res.next()) {

do {

// successfully in. do the right things.

} while (res.next());

} else {

// no results back. warn the user.

}

if (!resultSet.isAfterLast() ) {

System.out.println("No data");

}

对于空结果集,isAfterLast()也返回false,但是由于游标始终位于第一行之前,因此此方法似乎更清晰。

if(resultSet.first) {

} else {

system.out.println("No raw or resultSet is empty");

}

因为如果ResultSet没有原始值,则resultSet.first返回false。

但是它将光标移动到第一行是不必要的,并且可能使ob"重置"对象的进一步使用混乱并且可能丢失数据

ResultSet result = stmt.executeQuery(sqlQuery);

if (!result.next())

status ="ERROR";

else

status ="SUCCESS";

通过使用resultSet.next(),无论resultSet是否包含任何值,您都可以轻松获取结果

ResultSet resultSet = preparedStatement.executeQuery();

if(resultSet.next())

//resultSet contain some values

else

// empty resultSet

不要重复现有的答案。

最好的做法是检查第一行,以便在打算获取数据时可以避免跳过行的错误。类似于:if(!resultSet.first()){System.out.println(" no data"); }

我一直在尝试将当前行设置为第一个索引(使用主键)。我会建议

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

}

你的答案是什么?

我创建了以下方法来检查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);

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

if(CollectionUtils.isNotEmpty(resultList)){

/**

* do some stuff

*/

}

这将检查是否为空以及结果集条件为空。

有关更多详细信息,您可以参考以下文档。

实用工具

ResultSet不是集合。

为什么不使用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)"似乎很好。

你可以做这样的事情

boolean found = false;

while ( resultSet.next() )

{

found = true;

resultSet.getString("column_name");

}

if (!found)

System.out.println("No Data");

WAAAY太复杂了。

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()){....}时,将执行ResultSet的第一行,而在while(rs.next()){....}中的第一行之后,我们将从下一行获取结果。因此,我认为在if内部重新执行查询是更好的选择。

-1这不是一个更好的选择。为什么要查询数据库两次?如果两次呼叫之间的数据发生巨大变化怎么办?这很浪费。

最初,结果集对象(rs)指向BFR(在第一条记录之前)。一旦我们使用rs.next(),光标将指向第一条记录,而rs则保持" true"。使用while循环,您可以打印表的所有记录。检索完所有记录后,光标将移至ALR(最后一条记录之后),并将其设置为null。让我们考虑表中有2条记录。

if(rs.next()==false){

// there are no records found

}

while (rs.next()==true){

// print all the records of the table

}

简而言之,我们也可以将条件写为while(rs.next())。

您的while循环将没有机会在返回的第一行进行操作,这种方法似乎有些致命的缺陷。上面有很多建议都比这更好。

  • 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>"); } }
好的,您需要使用JavaJDBC库连接到源数据库,并执行查询并将数据复制到目标数据库。您可以按照以下步骤进行操作: 1. 导入JDBC库:将JDBC驱动程序库添加到您的项目中。您可以在官方JDBC库的网站上下载适合您的数据库的驱动程序。 2. 连接源数据库:使用JDBC API中的DriverManager类和Connection接口连接到源数据库。在连接字符串中指定数据库名称、用户名和密码。 3. 执行查询:使用JDBC API中的Statement接口或PreparedStatement接口执行查询。 4. 复制数据:使用JDBC API中的ResultSet接口获取查询结果,并使用JDBC API中的PreparedStatement接口将数据插入目标数据库。 以下是一个示例代码片段,演示如何使用JavaJDBC库连接到源数据库,并执行查询并将数据复制到目标数据库: ```java import java.sql.*; public class JDBCExample { public static void main(String[] args) { Connection sourceConn = null; Connection targetConn = null; try { // Connect to source database sourceConn = DriverManager.getConnection("jdbc:source_db_url", "username", "password"); // Connect to target database targetConn = DriverManager.getConnection("jdbc:target_db_url", "username", "password"); // Execute query on source database Statement stmt = sourceConn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM source_table"); // Copy data to target database PreparedStatement pstmt = targetConn.prepareStatement("INSERT INTO target_table VALUES (?, ?)"); while(rs.next()) { pstmt.setInt(1, rs.getInt("column1")); pstmt.setString(2, rs.getString("column2")); pstmt.executeUpdate(); } } catch(SQLException e) { e.printStackTrace(); } finally { try { if(sourceConn != null) { sourceConn.close(); } if(targetConn != null) { targetConn.close(); } } catch(SQLException e) { e.printStackTrace(); } } } } ``` 请注意,此示例代码仅供参考,并且需要根据您的特定情况进行修改。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值