473,395 Members | 1,941 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

empty resultset

Hello,
I'm new in java. my actual problem is :
how can i test if a resultset is empty?

I have tested:

rs == null
rs.next()
rs.isAfterLast()
rs.last()

but the result is the exception java.lang.NullPointerException
Mar 28 '07 #1
12 16693
r035198x
13,262 8TB
Hello,
I'm new in java. my actual problem is :
how can i test if a resultset is empty?

I have tested:

rs == null
rs.next()
rs.isAfterLast()
rs.last()

but the result is the exception java.lang.NullPointerException
From the docs

"The next method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result set"
Mar 28 '07 #2
Thanks
but if i try to iterate i obtain the java.lang.NullPointerException. It is possible test the resutset if empty or no without throw the exception?
Mar 28 '07 #3
r035198x
13,262 8TB
Thanks
but if i try to iterate i obtain the java.lang.NullPointerException. It is possible test the resutset if empty or no without throw the exception?
Let's see your code. Are you initializing the resultset properly? executeQuery never returns null.
Mar 28 '07 #4
this is the code:

ResultSet rs = dbConn.EseguiLettura(strSql);
dbConn.closeConn();
while (rs.next())
{
System.out.println("not empty");
}

and the method call is

public ResultSet EseguiLettura(String sSqlToExecute) throws SQLException
{
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSI TIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery(sSqlToExecute);
rs.close();
stmt.close();
return rs;
}
Mar 28 '07 #5
r035198x
13,262 8TB
this is the code:

ResultSet rs = dbConn.EseguiLettura(strSql);
dbConn.closeConn();
while (rs.next())
{
System.out.println("not empty");
}

and the method call is

public ResultSet EseguiLettura(String sSqlToExecute) throws SQLException
{
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSI TIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery(sSqlToExecute);
rs.close();
stmt.close();
return rs;
}
1.)Why are you returning a closed resultset?
2.)You should really post the full code for it to be obvious where the error is. I can remove it afterwards if you want.
3.)When posting the code please remember to use code tags.
Mar 28 '07 #6
Thanks

This is the code


Expand|Select|Wrap|Line Numbers
  1.  
  2. import java.util.*;
  3. import java.sql.*;
  4. public class EseguiProcesso 
  5. {
  6.   private static String msgInfo="Inizio EseguiProcesso.";
  7.   private static String strSql=null;
  8.  
  9.  public static void main(String args[]) throws OwnException
  10.     {
  11.       Configurazione config;
  12.       DbConn dbConn;
  13.       Processo processo;
  14.       String sDataElab=null;
  15.       String sNomeProcesso=null;
  16.       String sFlagForzatura=null;
  17.       LeggiStringaSQL leggiStrSql;
  18.       try 
  19.       {
  20.          System.out.println(msgInfo);
  21.          config = new Configurazione();
  22.         if (args.length!=0)
  23.         {
  24.           config.Valorizza(args[0]);
  25.         }
  26.         else
  27.         {
  28.           throw new OwnException("Attenzione occorre fornire il nome del file di configurazine.");
  29.         }
  30.          msgInfo="Lettura Parametri.";
  31.         if (args.length==config.getnumParam() )
  32.         {
  33.           for (int i=0; i < args.length; i++)
  34.           {
  35.            if (i==1)
  36.            {
  37.              sNomeProcesso = args[i];
  38.            }
  39.            if (i==2)
  40.            {
  41.              verificaData(args[i]);
  42.              sDataElab = args[i];
  43.            }
  44.            if (i==3)
  45.            {
  46.              sFlagForzatura = args[i];
  47.            }
  48.  
  49.           }
  50.         }
  51.         else
  52.         {
  53.           throw new OwnException("Numero di parametri attesi errato.");
  54.         }
  55.          msgInfo="Connessione al database.";
  56.          dbConn = new DbConn(config.gettipoDB(), config.geturlDB(),config.getusrDB(),config.getpwdDB());
  57.         dbConn.openConn();
  58.         leggiStrSql = new LeggiStringaSQL();
  59.         String arrParmSql[] = {sDataElab,sNomeProcesso};
  60.           msgInfo="Lettura Select per Processo.";
  61.         strSql=leggiStrSql.EstraiStrSQL("[PROCESSO]", arrParmSql);
  62.          msgInfo="Lettura Recordset per Processo.";
  63.          ResultSet rs = dbConn.EseguiLettura(strSql);
  64.         dbConn.closeConn();
  65.         while (rs.next())
  66.         {
  67.           System.out.println("nullo");
  68.         }
  69.         processo = new Processo(sNomeProcesso,sDataElab,dbConn);
  70.         System.out.println("Fine EseguiProcesso.");
  71.         System.exit(0);    
  72.       }
  73.       catch (SQLException exc) 
  74.       {
  75.         System.out.println(msgInfo + " Errore : " + exc.getErrorCode() + " :"+ exc.getMessage());
  76.         System.exit(1);    
  77.       }
  78.     }
  79.  
  80.     public static void verificaData(String dataToVerify) throws OwnException
  81.     {
  82.       int anno;
  83.       int mese;
  84.       int giorno;
  85.       String msg=null;
  86.       int daysPerMonth[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
  87.  
  88.       try
  89.       {
  90.         msg="Funzione verificaData. Valorizzazione anno :"+dataToVerify+" ";
  91.         anno = Integer.valueOf(dataToVerify.substring(0,4)).intValue();
  92.         msg="Funzione verificaData. Valorizzazione mese :"+dataToVerify+" ";
  93.         mese = Integer.valueOf(dataToVerify.substring(4,6)).intValue();
  94.         msg="Funzione verificaData. Valorizzazione giorno :"+dataToVerify+" ";
  95.         giorno = Integer.valueOf(dataToVerify.substring(6,8)).intValue();
  96.         msg="Funzione verificaData. Verifica mese :"+dataToVerify+" ";
  97.         if ((mese<1)|| (mese>12))
  98.         {
  99.            throw new OwnException("Mese errato.");
  100.         }
  101.         msg="Funzione verificaData. Verifica giorno :"+dataToVerify+" ";        
  102.  
  103.         if (!( giorno > 0 && giorno <= daysPerMonth[ mese ] ))
  104.         {
  105.          if (mese==2)
  106.          {
  107.            if (!( mese == 2 && giorno == 29 && ( anno % 400 == 0 || ( anno % 4 == 0 && anno % 100 != 0 ) ) ))
  108.             {
  109.               throw new OwnException("Numero di giorni errato (anno bisestile).");
  110.             }
  111.           }
  112.           else
  113.           {
  114.             throw new OwnException("numero di giorni errato.");
  115.           }
  116.         }
  117.  
  118.  
  119.       }
  120.       catch (Exception exc)
  121.       {
  122.        throw new OwnException(msg +exc.getMessage());
  123.       }
  124.     }
  125. }
  126.  
  127. // DbConn Class
  128.  
  129. import java.sql.*;
  130. import java.io.*;
  131. import oracle.jdbc.*;
  132. import oracle.jdbc.pool.*;
  133. public class DbConn 
  134. {
  135.   private String sDBType;
  136.   private String sServerURL;
  137.   private String sUser;
  138.   private String sPwd;
  139.   private String sMsg;
  140.   private String nome="Classe DbConn.";
  141.   private Connection conn;
  142.   private OracleDataSource ods;
  143.   public DbConn(String dbType, String serverUrl, String user, String pwd)
  144.   {
  145.       sMsg="Funzione conn. Valorizzazione Parametri.";
  146.       sDBType=dbType;
  147.       sServerURL=serverUrl;
  148.       sUser=user;
  149.       sPwd=pwd;
  150.   }
  151.  
  152.   public void openConn() throws SQLException,OwnException
  153.   {
  154.     try
  155.     {
  156.       sMsg="Funzione conn. Creazione connessione.";
  157.       if ((sDBType.trim()).compareTo("ORACLE")==0 )
  158.       {
  159.         ods = new OracleDataSource();
  160.         ods.setURL(sServerURL);
  161.         conn = ods.getConnection(sUser,sPwd);
  162.       }
  163.       else
  164.       {
  165.         throw new OwnException("Attenzione!!! Tipo di Database non Gestito. "+sDBType);
  166.       }
  167.     }
  168.     catch(SQLException e)
  169.     {
  170.       throw new OwnException(nome+" "+sMsg+ " " + e.getErrorCode() + " :"+e.getMessage());
  171.     }
  172.   }
  173.   public void closeConn() throws SQLException,OwnException
  174.   {
  175.     try
  176.     {
  177.       sMsg="Funzione closeConn. Chiusura connessione.";
  178.       conn.close();
  179.     }
  180.     catch(SQLException e)
  181.     {
  182.       throw new OwnException(nome+" "+sMsg+ " "+ e.getErrorCode() + " :"+e.getMessage());
  183.     }
  184.   }
  185.   public ResultSet EseguiLettura(String sSqlToExecute) throws SQLException
  186.   {
  187.       Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
  188.       ResultSet rs = stmt.executeQuery(sSqlToExecute);
  189. //      rs.close();
  190.       stmt.close();
  191.       return rs;
  192.   }
  193.  
  194.  
  195.  
Mar 28 '07 #7
r035198x
13,262 8TB
Thanks

This is the code


Expand|Select|Wrap|Line Numbers
  1.  
  2. import java.util.*;
  3. import java.sql.*;
  4. public class EseguiProcesso 
  5. {
  6.   private static String msgInfo="Inizio EseguiProcesso.";
  7.   private static String strSql=null;
  8.  
  9.  public static void main(String args[]) throws OwnException
  10.     {
  11.       Configurazione config;
  12.       DbConn dbConn;
  13.       Processo processo;
  14.       String sDataElab=null;
  15.       String sNomeProcesso=null;
  16.       String sFlagForzatura=null;
  17.       LeggiStringaSQL leggiStrSql;
  18.       try 
  19.       {
  20.          System.out.println(msgInfo);
  21.          config = new Configurazione();
  22.         if (args.length!=0)
  23.         {
  24.           config.Valorizza(args[0]);
  25.         }
  26.         else
  27.         {
  28.           throw new OwnException("Attenzione occorre fornire il nome del file di configurazine.");
  29.         }
  30.          msgInfo="Lettura Parametri.";
  31.         if (args.length==config.getnumParam() )
  32.         {
  33.           for (int i=0; i < args.length; i++)
  34.           {
  35.            if (i==1)
  36.            {
  37.              sNomeProcesso = args[i];
  38.            }
  39.            if (i==2)
  40.            {
  41.              verificaData(args[i]);
  42.              sDataElab = args[i];
  43.            }
  44.            if (i==3)
  45.            {
  46.              sFlagForzatura = args[i];
  47.            }
  48.  
  49.           }
  50.         }
  51.         else
  52.         {
  53.           throw new OwnException("Numero di parametri attesi errato.");
  54.         }
  55.          msgInfo="Connessione al database.";
  56.          dbConn = new DbConn(config.gettipoDB(), config.geturlDB(),config.getusrDB(),config.getpwdDB());
  57.         dbConn.openConn();
  58.         leggiStrSql = new LeggiStringaSQL();
  59.         String arrParmSql[] = {sDataElab,sNomeProcesso};
  60.           msgInfo="Lettura Select per Processo.";
  61.         strSql=leggiStrSql.EstraiStrSQL("[PROCESSO]", arrParmSql);
  62.          msgInfo="Lettura Recordset per Processo.";
  63.          ResultSet rs = dbConn.EseguiLettura(strSql);
  64.         dbConn.closeConn();
  65.         while (rs.next())
  66.         {
  67.           System.out.println("nullo");
  68.         }
  69.         processo = new Processo(sNomeProcesso,sDataElab,dbConn);
  70.         System.out.println("Fine EseguiProcesso.");
  71.         System.exit(0);    
  72.       }
  73.       catch (SQLException exc) 
  74.       {
  75.         System.out.println(msgInfo + " Errore : " + exc.getErrorCode() + " :"+ exc.getMessage());
  76.         System.exit(1);    
  77.       }
  78.     }
  79.  
  80.     public static void verificaData(String dataToVerify) throws OwnException
  81.     {
  82.       int anno;
  83.       int mese;
  84.       int giorno;
  85.       String msg=null;
  86.       int daysPerMonth[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
  87.  
  88.       try
  89.       {
  90.         msg="Funzione verificaData. Valorizzazione anno :"+dataToVerify+" ";
  91.         anno = Integer.valueOf(dataToVerify.substring(0,4)).intValue();
  92.         msg="Funzione verificaData. Valorizzazione mese :"+dataToVerify+" ";
  93.         mese = Integer.valueOf(dataToVerify.substring(4,6)).intValue();
  94.         msg="Funzione verificaData. Valorizzazione giorno :"+dataToVerify+" ";
  95.         giorno = Integer.valueOf(dataToVerify.substring(6,8)).intValue();
  96.         msg="Funzione verificaData. Verifica mese :"+dataToVerify+" ";
  97.         if ((mese<1)|| (mese>12))
  98.         {
  99.            throw new OwnException("Mese errato.");
  100.         }
  101.         msg="Funzione verificaData. Verifica giorno :"+dataToVerify+" ";        
  102.  
  103.         if (!( giorno > 0 && giorno <= daysPerMonth[ mese ] ))
  104.         {
  105.          if (mese==2)
  106.          {
  107.            if (!( mese == 2 && giorno == 29 && ( anno % 400 == 0 || ( anno % 4 == 0 && anno % 100 != 0 ) ) ))
  108.             {
  109.               throw new OwnException("Numero di giorni errato (anno bisestile).");
  110.             }
  111.           }
  112.           else
  113.           {
  114.             throw new OwnException("numero di giorni errato.");
  115.           }
  116.         }
  117.  
  118.  
  119.       }
  120.       catch (Exception exc)
  121.       {
  122.        throw new OwnException(msg +exc.getMessage());
  123.       }
  124.     }
  125. }
  126.  
  127. // DbConn Class
  128.  
  129. import java.sql.*;
  130. import java.io.*;
  131. import oracle.jdbc.*;
  132. import oracle.jdbc.pool.*;
  133. public class DbConn 
  134. {
  135.   private String sDBType;
  136.   private String sServerURL;
  137.   private String sUser;
  138.   private String sPwd;
  139.   private String sMsg;
  140.   private String nome="Classe DbConn.";
  141.   private Connection conn;
  142.   private OracleDataSource ods;
  143.   public DbConn(String dbType, String serverUrl, String user, String pwd)
  144.   {
  145.       sMsg="Funzione conn. Valorizzazione Parametri.";
  146.       sDBType=dbType;
  147.       sServerURL=serverUrl;
  148.       sUser=user;
  149.       sPwd=pwd;
  150.   }
  151.  
  152.   public void openConn() throws SQLException,OwnException
  153.   {
  154.     try
  155.     {
  156.       sMsg="Funzione conn. Creazione connessione.";
  157.       if ((sDBType.trim()).compareTo("ORACLE")==0 )
  158.       {
  159.         ods = new OracleDataSource();
  160.         ods.setURL(sServerURL);
  161.         conn = ods.getConnection(sUser,sPwd);
  162.       }
  163.       else
  164.       {
  165.         throw new OwnException("Attenzione!!! Tipo di Database non Gestito. "+sDBType);
  166.       }
  167.     }
  168.     catch(SQLException e)
  169.     {
  170.       throw new OwnException(nome+" "+sMsg+ " " + e.getErrorCode() + " :"+e.getMessage());
  171.     }
  172.   }
  173.   public void closeConn() throws SQLException,OwnException
  174.   {
  175.     try
  176.     {
  177.       sMsg="Funzione closeConn. Chiusura connessione.";
  178.       conn.close();
  179.     }
  180.     catch(SQLException e)
  181.     {
  182.       throw new OwnException(nome+" "+sMsg+ " "+ e.getErrorCode() + " :"+e.getMessage());
  183.     }
  184.   }
  185.   public ResultSet EseguiLettura(String sSqlToExecute) throws SQLException
  186.   {
  187.       Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
  188.       ResultSet rs = stmt.executeQuery(sSqlToExecute);
  189. //      rs.close();
  190.       stmt.close();
  191.       return rs;
  192.   }
  193.  
  194.  
  195.  
Now go over the exception trace again and indicate which line threw the exception.
Mar 28 '07 #8
this is the error

Exception in thread "main" java.lang.NullPointerException
at oracle.jdbc.driver.UpdatableResultSet.next(Updatab leResultSet.java:251)
at EseguiProcesso.main(EseguiProcesso.java:72)


and this is the line:
Expand|Select|Wrap|Line Numbers
  1.  
  2. while (rs.next())
  3.         {
  4.           System.out.println("nullo");
  5.         }
  6.  
Mar 28 '07 #9
sicarie
4,677 Expert Mod 4TB
dbConn.closeConn();
while (rs.next())
{
System.out.println("not empty");
}
I think your problem lies in that ResultSet requires a persistent connection - you close the connection (dbConn.closeConn(); ) and you will lose the pointer to the ResultSet. You want to close the connection after you parse your rs.
Mar 28 '07 #10
r035198x
13,262 8TB
I think your problem lies in that ResultSet requires a persistent connection - you close the connection (dbConn.closeConn(); ) and you will lose the pointer to the ResultSet. You want to close the connection after you parse your rs.
Yeah the resultset is closed, from the docs

"A ResultSet object is automatically closed by the Statement object that generated it when that Statement object is closed, re-executed, or is used to retrieve the next result from a sequence of multiple results"
Mar 28 '07 #11
Thank you
Yes, the problem seem to be this.

i have commented also the line related to the closure of the Statement and now it seem correct.


Expand|Select|Wrap|Line Numbers
  1.   public ResultSet EseguiLettura(String sSqlToExecute) throws SQLException
  2.   {
  3.       Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
  4.       ResultSet rs = stmt.executeQuery(sSqlToExecute);
  5. //      rs.close();
  6. //      stmt.close();
  7.       return rs;
  8.   }
  9.  
  10.  
Thank you
Mar 28 '07 #12
sicarie
4,677 Expert Mod 4TB
Thank you
Yes, the problem seem to be this.

i have commented also the line related to the closure of the Statement and now it seem correct.


Expand|Select|Wrap|Line Numbers
  1.   public ResultSet EseguiLettura(String sSqlToExecute) throws SQLException
  2.   {
  3.       Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
  4.       ResultSet rs = stmt.executeQuery(sSqlToExecute);
  5. //      rs.close();
  6. //      stmt.close();
  7.       return rs;
  8.   }
  9.  
  10.  
Thank you
Glad to have helped, keep in mind that it is comsidered good practice to close the rs/con when you are done.

please post again if you have any other troubles (or if you see something you can help with).
Mar 28 '07 #13

Sign in to post your reply or Sign up for a free account.

Similar topics

0
by: Phil Powell | last post by:
Based upon an article I read in http://archives.neohapsis.com/archives/mysql/2004-q1/0337.html I am trying to retrieve an "empty row" of fields from a table that may be empty. If I have this...
4
by: P Adhia | last post by:
Hello, If the explain shows that DB2 needs to sort the result of a cursor, does that always happen? i.e. if the resultset of the cursor is empty, does the sort have any overhead? It appears...
1
by: rafikki3 | last post by:
I have a java web application that is using the db2jcc driver to get a connection to a DB2 database that is located on an RS 6000 server. The here is a portion of the code that is giving me a...
4
by: _link98 | last post by:
Problem: java ResultSet cursor from SQL/PL stored-procedure is FORWARD_ONLY. Is it possible to have ResultSet cursors from SQL/PL procedures to scroll forward and backwards? Perhaps I am missing...
12
by: robertino | last post by:
Hi all, I've put together a few SPs to produce a BOM (bill of materials) listing, which together use a couple of global temp tables, and return the results from a cursor. Here's the code: ...
6
by: abctech | last post by:
My requirement is such that any user must not be allowed to save the same record twice. For this what I do is as soon as some user fills up the page and clicks 'Save' I invoke a Servlet which...
2
by: stigwulff | last post by:
I have made a ASP.NET ver. 2 webservice that runs on an Exchange 2003 server. In that webservice I want to get the size of the mailboxes on the Exchange server. I try to use WMI and the...
6
by: joerg | last post by:
Hello world, my program connects to a db2 database and needs to find out the column names and data types for a specific table. The code works fine with mysql and derby, but returns an empty...
4
guillermobytes
by: guillermobytes | last post by:
hi, i was wondering which type of join should i use to get an empty result set when there is no record in one of the tables i.e : i have two tables : Element and Attribute the table Element...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.