tags:

views:

73

answers:

6
import java.net.URL;
import java.net.URLConnection;
import java.sql.*;
public class searchlink{
public static void main(String args[]) throws Exception {
    //String link="http://hosted.ap.org";
    Connection con=null;
    Statement stmt=null;
    Statement stmtR=null;
    if(con==null){
            SQLConnection.setURL("jdbc:sqlserver://192.168.2.53\\SQL2005;user=sa;password=365media;DatabaseName=LN_ADWEEK");
            con=SQLConnection.getNewConnection();
            stmt=con.createStatement();
            stmtR=con.createStatement();
    }
    ResultSet rs;
    rs=stmt.executeQuery("select url from urls where url='http://www.topix.com/rty/elyria-oh'");
    while(rs.next()){
    String mem=rs.getString(1);
    System.out.println("Result is "+mem);}
}
}

The above program prints the output if the query returns a row. If the query does not return any, the program stops without printing anything.

Instead of it getting stopped without printing anything, I want the program to identify that the query has returned nothing and print the output saying something like this " There is nothing returned after SQL query execution ".

How to identify using some method or variable that the query has been executed without returning any row?

+1  A: 
if (rs.hasNext())
{
    while(rs.next())
   {
    String mem=rs.getString(1);
    System.out.println("Result is "+mem);
   }

}
else
{
   System.out.println("There is nothing returned after SQL query execution ");
}

maybe~

Eton B.
I don't believe the ResultSet will be null, but rather instantiated and empty.
Matthew Vines
Thanks, edited my reponse accordingly.
Eton B.
Still not right. "rs.next()" will move it to the next row. You mean "rs.hasNext()"
Jeff Walker
A: 

The first (rs.next()) will tell you if any data was returned. React to that one, then loop through the rest (if there are any).

Below I extract the logic for what to do when there is a row into a separate method, and then call that after the "if" and within each "where".

   . . .


   ResultSet rs;
   rs=stmt.executeQuery("select url from urls where url='http://www.topix.com/rty/elyria-oh'");
   if (rs.next() {
      printRow(rs);
      while(rs.next()){
          printRow(rs);
      }
    }
    else {
        System.out.println("no data returned");
    }
  }

  static public printRow(ResultSet rs) {
    String mem=rs.getString(1);
    System.out.println("Result is "+mem);}
  }   

}
Matthew Flynn
+6  A: 
bool hasRows = false;
while(rs.next()){
  hasRows = true;
  // do other stuff required.
}

if(!hasRows)
{
  // do stuff when no rows present.
}

-- or

if(!rs.next())
{
  // do stuff when no rows prsent.
}
else
{
  do{
  // do stuff required
  }while(rs.next());
}

keeping in mind that the check if(!rs.next()) will advance the cursor in the result set. Don't advance it again before you get the values.

Matthew Vines
Thanks Mathew :)
LGAP
+1 for the elegant second version. Unfortunately, the logic is harder to read, and you missed a semicolon.
tc.
@tc thanks, got that semicolon in there, I always forget them in do-whiles. I agree it's not immediately obvious what you are doing in the second example. Like anything else it's all about personal tastes and team standards which side of the readability / elegance spectrum you choose to error on (though thankfully they aren't always mutually exclusive).
Matthew Vines
A: 

Place a counter in your loop...

int count = 0;

while(rs.next()){

count++;

String mem=rs.getString(1);   
System.out.println("Result is "+mem);}
.
.
.

}

then ... if (count==0) { // show your message "There is nothing returned after SQL query execution" }

Any call to rs.next() moves the cursor so if (rs.next() == false) would bump you one ahead and make you skip the first result if you had 2 or more or miss it intirely if you had one result.

Good Luck,

Rick

Rick Schmid
Which fails if it returns 2**32 rows.
tc.
With all due respect the statement while(rs.next()) works for 0,1,many results... count is incremented for any scenerio of 1 or more so testing count for non-zero yeilds the answer that you either found 1 or more records or none. At least thats what it looks like to me.Rick
Rick Schmid
A: 
boolean got_result = false;
while (...) {
  got_result = true;
  ...
}
if (!got_result) {
  ...
}
tc.
+1  A: 

The normal JDBC idiom is to collect the results in a collection like List<Entity>. The another normal idiom is to properly close resources in finally. Your code is leaking DB resources. If you run this repeatedly in a short time, then the DB will run out of resources.

Here's a kickoff example:

public List<Entity> list() throws SQLException {
    // Declare resources.
    Connection connection = null;
    Statement statement = null;
    ResultSet resultSet = null;
    List<Entity> entities = new ArrayList<Entity>();

    try {
        // Acquire resources.
        connection = database.getConnection();
        statement = connection.createStatement("SELECT id, name, value FROM entity");
        resultSet = statement.executeQuery();

        // Gather data.
        while (resultSet.next()) {
            Entity entity = new Entity(); 
            entity.setId(resultSet.getLong("id"));
            entity.setName(resultSet.getString("name"));
            entity.setValue(resultSet.getInteger("value"));
            entities.add(entity);
        }
    } finally {
        // Close resources in reversed order.
        if (resultSet != null) try { resultSet.close(); } catch (SQLException logOrIgnore) {}
        if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {}
        if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
    }

    // Return data.
    return entities;
}

This way you can use the usual List methods to determine the state of the result:

List<Entity> entities = entityDAO.list();

if (entities.isEmpty()) {
    // It is empty!
if (entities.size() == 1) {
    // It has only one row!
} else {
    // It has more than one row!
}

See also:

BalusC
Thanks Balus... Ur answers are really helpful and very brief.Hope you will guide me till I become a good java programmer :)
LGAP
You're welcome.
BalusC