Mysql Result set Error - java

I am executing a block of code where I need to retrieve a set of users from database and do some stuff with them. Very simple scenario.
The problem is that although I use while(rs.next()) , when rs.next() reaches null my program tries to continue with the code inside while clause and exits with Null Exception.
Why is that happening? Is something broken in my code that I cannot figure out?
Please, notice that rs is never null. At the beginning prints at the console all the contents of rs but when it reaches the end it returns null exception.
try {
String sql = "select distinct userid from userinfo";
stmt1 = conn.createStatement();
try (ResultSet rs = stmt1.executeQuery(sql)) {
while (rs.next()) {
String mentionsIDs = (rs.getString("mentions")).trim();
try{
if (!mentionsIDs.isEmpty() ){
System.out.println(mentionsIDs);
String[] arr = mentionsIDs.split("\\s+");
if(isNumeric(arr[0])){
System.out.println(arr[0]);
sources.add(Long.parseLong(arr[0]));
}
}
}
catch(Exception ex){
Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
}
}
rs.close();
}
Any help is appreciated.

Move String mentionsIDs = (rs.getString("mentions")).trim(); inside the try block then catch NullPointerException.

You must also check that the result set indeed have some results in it. Put a condition over your while loop which checks that rs is not null.
if(rs!=null) {
while(rs.next()) {
... Process
}
} else {
System.out.println("The query returned 0 results");
}
In your code:
String sql = "select distinct userid from userinfo";
stmt1 = conn.createStatement();
try (ResultSet rs = stmt1.executeQuery(sql)) {
if(rs!=null) {
while (rs.next()){
String mentionsIDs = (rs.getString("mentions")).trim();
try{
if (!mentionsIDs.isEmpty() ){
System.out.println(mentionsIDs);
String[] arr = mentionsIDs.split("\\s+");
if(isNumeric(arr[0])){
System.out.println(arr[0]);
sources.add(Long.parseLong(arr[0]));
}
}
}
catch(Exception ex){
Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
}
}
rs.close();
}

Related

java: display the elements from a database

I wrote some java code to display database, when I run the code it gives me just the last element of database , but I wanna display all elements of table
the code :
public String RecupererPuissance() {
try {
Connection con = myDbvoiture.getConnection();
String queryPattern ="select Power from bd_voiture";
PreparedStatement pstmt = con.prepareStatement(queryPattern);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
puissance=rs.getString("Power");
System.out.println(puissance);
}
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
return puissance;
}
What should I do? Can anyone please help me to display all values?
Thank you for helping me.
I think the problem is with your code that the value of puissance is overwritten every time you get the next element. Only the last value is returned. You should put the results into a list and return the whole list:
public List<String> RecupererPuissance() {
List<String> puissances = new ArrayList<String>();
try {
Connection con = myDbvoiture.getConnection();
String queryPattern ="select Power from bd_voiture";
PreparedStatement pstmt = con.prepareStatement(queryPattern);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
puissance = rs.getString("Power");
puissances.add(puissance);
System.out.println(puissance);
}
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
return puissances;
}
public String RecupererPuissance() {
try {
Connection con = myDbvoiture.getConnection();
String queryPattern ="select Power from bd_voiture";
PreparedStatement pstmt = con.prepareStatement(queryPattern);
ResultSet rs = pstmt.executeQuery();
rs.first();
int count=0;
while (rs.next()) {
System.out.println("count = "+count);
count+=1;
puissance=rs.getString("Power");
System.out.println(puissance);
}
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
return puissance;
}
If you see count printed only 1 time :
it would mean that you have only 1 row in column Power
and you maybe referring to the wrong column in your code

Assign to string instead of resultset for jdbc query

I need to get the output of a jdbc query, but wherever I google, it returns a resultset. But, its just a single row. Here is my query
ResultSet rsLocationId = null;
rsLocationId = stmtLocation.executeQuery("SELECT apmcid FROM userbusinesstoapmc WHERE userbusinessid='"+userBusinessKey+"'");
It should return a single record as a string. How can I convert it? Any ideas would be greatly appreciated.
I suggest you use PreparedStatement and bind the parameter, currently you are vulnerable to SQL Injection attacks.
PreparedStatement ps = null;
ResultSet rs = null;
String result = null;
final String sql = "SELECT apmcid FROM userbusinesstoapmc "
+ "WHERE userbusinessid=?";
try {
ps = conn.prepareStatement(sql);
ps.setString(1, userBusinessKey);
rs = ps.executeQuery();
if (rs.next()) {
result = rs.getString("apmcid");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
you can try like this
ResultSet rsLocationId = null;String result="";
rsLocationId = stmtLocation.executeQuery("SELECT apmcid FROM userbusinesstoapmc WHERE userbusinessid='"+userBusinessKey+"'");
if(rsLocationId.next())
{
result=rsLocationId.getString('apmcid');
}
Even though your particular query only returns a single column, presumably some CHAR type if you expect the result to be a String, the executeQuery method returns a result set object, not a String object. So, you have to process the result set to get your String data. SpringLearner has provided a good example of how to do this.

java.sql.SQLException: Exhausted Resultset error

I'm facing the problem with this exception java.sql.SQLException: Exhausted Resultset in following code. I'm sure my query returns only one value. Even If I don't use rs.next(); it throws the error java.sql.SQLException: ResultSet.next was not called. Could you please help?
FYI, I'm using the another result set in main where this menthod from another class is called. will it affect?
Thanks
public static String getdispname(Connection conn, String resname)
throws SQLException, Exception {
//String resname = "";
String returnValue = "";
String querystring = "";
//Query to select the displayname from resid
querystring += "select distinct display_name";
querystring += " from cust_rally_team_member";
querystring += " where display_name like '%"+ resid +"%'";
// Create select statement
Statement stmt = conn.createStatement();
try {
// Execute statement
ResultSet rs = stmt.executeQuery(querystring);
if (rs!= null) {
while (rs.next()) {
returnValue = rs.getString("display_name");
} catch (SQLException ex) {
throw new SQLException(ex);
} catch (Exception ex) {
throw new Exception(ex);
}
// Close statement
finally {
stmt.close();
}
return returnValue;
Try as
if (rs! = null) {
while (rs.next()) {
returnValue = rs.getString("display_name");
}
......
Try:
returnValue = rs.next() ? rs.getString("display_name") : null;
You don't need to check if the rs is null. It won't be - assuming the executeQuery() returned rather than raising an exception. (Though the returned result set might have 0 rows).
You also don't need to loop over the result set, assuming you really know that you expect back a single row. (Though, given the query, that seems unlikely.)
use by your modification like below
if (rs != null && rs.first()) {
do {
returnValue = rs.getString(("display_name");
} while (rs.next());
}
I am using Oracle 10g database , i found same error "java.sql.SQLException: Exhausted Resultset error". I just grant permission in database and solved my probblem.
SQL> grant insert,update,delete on "table-name" to "database_name";

resultset isn't going into while loop and set the value

Observing a strange behavior of this piece of code,because resultset is not giving the null value(doing SOP it's clear)but not going into while loop(that is quite strange!)and it's simple dao class,it's not able to set the value in user object:
public class DAO{
public List<User> searchAllUsers(int offset ,int noOfRecords, String column, String value){
String query="select SQL_CALC_FOUND_ROWS * from info where '"+column+"' like '%"+value+"%' order by serialNo asc limit " + offset + " , " + noOfRecords;
// String query="select * from info where '"+select+"' like '%"+search+"%' order by serialNo asc";
System.out.println("1");
List<User> list = new ArrayList<User>();
User user=null;
try {
System.out.println("b4 Connection");
connection = getConnection();
System.out.println("After Connection");
stmt = connection.createStatement();
System.out.println("Create statement");
ResultSet rs=stmt.executeQuery(query);
if(rs!=null)
System.out.println("1> Hi rs:"+rs);
while(rs!= null && rs.next()){
System.out.println("hi...!!");
user=new User();
user.setSerial(rs.getInt(1));
System.out.println("Serial : "+rs.getInt(1));
user.setName(rs.getString(2));
user.setEmail(rs.getString(3));
user.setImei(rs.getString(4));
System.out.println("I'm here !");
user.setModel(rs.getString(5));
user.setManufacturer(rs.getString(6));
user.setOsversion(rs.getString(7));
user.setHdyk(rs.getString(8));
user.setDate(rs.getString(9));
user.setAppname(rs.getString(10));
list.add(user);
System.out.println("Last..");
}
rs.close();
rs = stmt.executeQuery("SELECT FOUND_ROWS()");
System.out.println("2> :" +rs);
if(rs.next()){
this.noOfRecords = rs.getInt(1);
System.out.println("3> :" +this.noOfRecords);
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
finally
{
try {
if(stmt != null)
stmt.close();
if(connection != null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return list;
}
public int getNoOfRecords() {
return noOfRecords;
}
}
And it corresponding output is :
1
b4 Connection
After Connection
Create statement
1> Hi rs:com.mysql.jdbc.JDBC4ResultSet#35e6e3
2> :com.mysql.jdbc.JDBC4ResultSet#c9630a
3> :0
Even I'm also using the same code like it for select All user's and that point of time I'm getting proper o/p.
Spending so many hours for it,but unable to resolve it-where I'm going wrong....so your review & comment will be always welcome.
That's because your query didn't fetch you any row. And hence rs.next() will return false, hence the execution will not go into the while loop:
while(rs!= null && rs.next())
And you don't have to check for rs != null. It won't be null. The stmt.executeQuery always returns a ResultSet. Just have rs.next() in your while:
while(rs.next())
And yes, you should use PreparedStatement for executing your query rather than Statement. Here's a tutorial which will help you get started.

How to find out if a Java ResultSet obtained is empty?

Class.forName("org.sqlite.JDBC");
Connection conn =
DriverManager.getConnection("jdbc:sqlite:userdata.db");
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery("SELECT * from table WHERE is_query_processed = 0;");
int rowcount = rs.getRow();
System.out.println("Row count = "+rowcount); // output 1
rs.first(); // This statement generates an exception
Why is it so?
The pattern I normally use is as follows:
boolean empty = true;
while( rs.next() ) {
// ResultSet processing here
empty = false;
}
if( empty ) {
// Empty result set
}
Here's a simple method to do it:
public static boolean isResultSetEmpty(ResultSet resultSet) {
return !resultSet.first();
}
Caveats
This moves the cursor to the beginning. But if you just want to test whether it's empty, you probably haven't done anything with it yet anyways.
Alternatively
Use the first() method immediately, before doing any processing.
ResultSet rs = stat.executeQuery("SELECT * from table WHERE is_query_processed = 0;");
if(rs.first()) {
// there's stuff to do
} else {
// rs was empty
}
References
ResultSet (Java Platform SE 6)
You can do this too:
rs.last();
int numberOfRows = rs.getRow();
if(numberOfRows) {
rs.beforeFirst();
while(rs.next()) {
...
}
}
while (results.next())
is used to iterate over a result set.so results.next() will return false if its empty.
Why is execution not entering the
while loop?
If your ResultSet is empty the rs.next() method returns false and the body of the while loop isn't entered regardless to the rownumber (not count) rs.getRow() returns. Colins example works.
Shifting the cursor forth and back to determine the amount of rows is not the normal JDBC practice. The normal JDBC practice is to map the ResultSet to a List of value objects each representing a table row entity and then just use the List methods to determine if there are any rows.
For example:
List<User> users = userDAO.list();
if (users.isEmpty()) {
// It is empty!
if (users.size() == 1) {
// It has only one row!
} else {
// It has more than one row!
}
where the list() method look like as follows:
public List<User> list() throws SQLException {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
List<User> users = new ArrayList<User>();
try {
connection = database.getConnection();
statement = connection.createStatement();
resultSet = statement.executeQuery(SQL_LIST);
while (resultSet.next()) {
User user = new User();
user.setId(resultSet.getLong("id"));
user.setName(resultSet.getString("name"));
// ...
users.add(user);
}
} finally {
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 users;
}
Also see this answer for other JDBC examples.
CLOSE_CURSORS_AT_COMMIT
public static final int CLOSE_CURSORS_AT_COMMIT
The constant indicating that ResultSet objects should be closed when the method Connection.commit is called.
Try with this:
ResultSet MyResult = null;
MyResult = Conexion.createStatement().executeQuery("Your Query Here!!!");
MyResult.last();
int NumResut = MyResult.getRow();MyResult.beforeFirst();
//Follow with your other operations....
This manner you'll be able work normally.
This checks if it's empty or not while not skipping the first record
if (rs.first()) {
do {
// ResultSet is not empty, Iterate over it
} while (rs.next());
} else {
// ResultSet is empty
}
May be you can convert your resultset object into String object and check whether is it empty or not.
`if(resultset.toString().isEmpty()){
// containg null result
}
else{
//This conains the result you want
}`

Categories

Resources