Check if ResultSet == null

hi,
which is the best way to check if a resultSet contains data?
for example:
ResultSet rs = ...; //get data
if( rs == null ) ... //doesn�t work
if( rs.equals(null) ) ... //doesn�t workso got anyone other ideas?
thx anyway
cu Errraddicator

java.sql.ResultSet is the result of a query execution by java.sql.Statement.
ResultSet cannot be null.
So, you should use the ResultSet.next() to check query result.
Sample Code.
try {
ResultSet rs = stmt.executeQuery("SELECT a, b FROM TABLE2");
while (rs.next()) {
int a = rs.getInt();
int b = rs.getInt();
catch (SQLException sqlex) {

Similar Messages

  • Checking if resultset still active?

    I want to return a ResultSet which basically handles some query i.e.
    public ResultSet doSomething(int chr, int startPos, int endPos, int strainsThreshold, float minGeneDensity) throws SQLException {
                    String someQuery = "";          
              // this should force incremental streaming of a large result set
              if(conn != null){
              stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY,
                       java.sql.ResultSet.CONCUR_READ_ONLY);
              stmt.setFetchSize(Integer.MIN_VALUE);
              return stmt.executeQuery(someQuery);
              }else
              return null;
         }This is running in a web application. However, if I stop a query running halfway through e.g. by pressing the stop button on the browser and then re-run the query the current resultSet is still active and throws an exception. Checking the API states that when the statement is fully executed the resultSet will be closed automatically but in this case it isn't. Is there any way of checking whether the resultSet is active or a way of closing it if a query ends prematurely?

    I suspect you need to change your function so it is tread safe. That way, a second sql request can be made even if the first one is pending. In your function, do the following (note all variables except dataSource are local variables so its thread safe): Note you can't return the resultSet because its closed within the function before the function is returned. Instead, copy the data from the resultSet into some type of array. (resultSet.getString("firstName") ) and return the array.
    public ArrayList myFunction(){
    Connection conn=null;
    PreparedStatement pstmt1= null;
    ResultSet resultSet=null
    ArrayList list1=new ArrayList();
    try{
    conn= dataSource.getConnection();
    pstmt1= conn.prepareStatement();
    resultSet= pstmt1.executeQuery();
    while(resultSet.next()){
    arrayList.add(resultSet.getString("lastName");
    return arrayList;
    } catch (SqlException e){
    } finally {
    if(rsultSet!=null)
    resultSet.close();
    if(pstmt1!=null)
    pstmt1.close();
    if(conn!=null)
    conn.close();
    Next, on your JSP page block you submit button from being clicked more than once until the page is re-rendered with the response from the server.
    If your query takes a long time to run and the user would consider trying to kill it, you cant. The database will execute the query to completion. I suggest instead limiting the amount of data fetched so its doesnt take so long. Add a filter to the page. Example: a textfield to filter by last Name. Enter 'B' in the textfield, and programmatically change the sql to 'select * from person where lastName like 'B%'.

  • How to check table is NULL or not when a form load?

    How to check table is NULL or not when a form load?
    I want to make the form when it load it check the data in table, if there are no data in table other form will be load.
    Sorry for bad English... 

    Maybe you can do this in form1's Form_Open event:
    if dcount("*", "table1") = 0 then
      Cancel = True
      Docmd.Openform "form2"
    end if
    -Tom. Microsoft Access MVP

  • JOptionPane Won't Display When ResultSet = null

    I wrote the following method to connect to an Access database via JDBC. Everything works properly except for the dialog box. It doesn't show up when the SQL query doesn't return anything. I've tried using the JOptionPane as an if, an else if, and an else without any luck. I know the syntax of the JOptionPane statement is correct, as it works in other parts of the program. Can anyone help? Thanks, Scott
    P.S. I know I should use a do while loop to populate the text fields...this is just a quick and dirty beta program.
         public void database(String query)
              try
              Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
              String dataSourceName = "testdatabase";
              String dbURL = "jdbc:odbc:" + dataSourceName;
              Connection con = DriverManager.getConnection(dbURL,"","");
              Statement s = con.createStatement();
              s.execute(query);
              ResultSet rs = s.getResultSet();
                   if (rs != null)
                   while ( rs.next() )
                   field2.setText(rs.getString(2));
                        field3.setText(rs.getString(3));
                        field4.setText(rs.getString(4));
                        field5.setText(rs.getString(5));
                        field6.setText(rs.getString(6));
                        field7.setText(rs.getString(7));
                        field8.setText(rs.getString(8));
                        field9.setText(rs.getString(9));
                        field10.setText(rs.getString(10));
                        field11.setText(rs.getString(11));
                        field12.setText(rs.getString(12));
                   if (rs == null)     JOptionPane.showMessageDialog(null, "UPC not found!");
                   s.close();
              con.close();
         catch (Exception err)
              System.out.println("ERROR: " + err);
         }

    I changed the line to:
    if(! rs.next()) JOptionPane.showMessageDialog(null,
    "UPC not found!");
    ...and now the dialog box pops up every time, even if
    there is data. Did I do something wrong with the
    syntax?Well no.. except that by the time you check you have already iterated through the result set and next returns false.
    I was thinking about something like this (and please in future use the code tags for pretty formatting like below... it makes it easier to read and the forum software will "eat" some of your code without it sometimes)
    boolean hasResults = false; // new line
    while ( rs.next() )
        hasResults = true; // there was at least one row
        field2.setText(rs.getString(2));
        field3.setText(rs.getString(3));
        field4.setText(rs.getString(4));
        field5.setText(rs.getString(5));
        field6.setText(rs.getString(6));
        field7.setText(rs.getString(7));
        field8.setText(rs.getString(8));
        field9.setText(rs.getString(9));
        field10.setText(rs.getString(10));
        field11.setText(rs.getString(11));
        field12.setText(rs.getString(12));
    if (!hasResults) JOptionPane.showMessageDialog(null, "UPC not found!");

  • Checking cell is null or not

    Hi ,
    Iam using poi to read excel sheet. Iam reading line by line of excel sheet using HssfUserModel.
    Here is my code
    int numberOfRows = sheet.getLastRowNum();
    for (int i = 1; i <= numberOfRows; i++)
      HSSFRow row = sheet.getRow(i);
    //  check whether row is null or not
      if (row != null)
        int numberOfCells = row.getLastCellNum();
         for(int j=0;j <= numberOfCells;j++)
             HSSFCell cell = row.getCell((short)j);
             short cellNumber = cell.getCellNum();
          //check whether cell is null or not
              if(cell!=null)
                if(cellNumber ==  myTradeConstants.scripCode_column_Number)
                   cell =row.getCell(myTradeConstants.scripCode_column_Number);
                   scripCode =cell.getStringCellValue();
                   System.out.println("scripCode:"+scripCode);
            else
                  System.out.println("nocellValue");
                  break;
    else
       System.out.println("rowBreak");
       break;
    }My Excel sheet is also having so many number of rows. But it is displaying only first row of the excel sheet. n displaying "nullpointerException".
    why iam getting nullPointer Exception.
    I want to check whether a cell is having data or not.
    can anybody guide me in right dircection.
    regards,
    ramu.

    import java.io.FileInputStream;
    import java.io.IOException;
    import java.util.Iterator;
    import org.apache.poi.hssf.usermodel.HSSFCell;
    import org.apache.poi.hssf.usermodel.HSSFRow;
    import org.apache.poi.hssf.usermodel.HSSFSheet;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.poifs.filesystem.POIFSFileSystem;
    public class cellCheck {
    * @param args
    public static void main(String[] args) {
              // TODO Auto-generated method stub
    try {
        POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(
                             args[0]));
        HSSFWorkbook workbook = new HSSFWorkbook(fs);
        HSSFSheet sheet = workbook.getSheet("Main");          // HSSFRow row = sheet.getRow(1);
         int numberOfRows = sheet.getLastRowNum();
       System.out.println("numberOfRowsInThe Sheet" + numberOfRows);
         String scripCode = null;
        for (int i = 1; i <= numberOfRows; i++)
         HSSFRow row = sheet.getRow(i);
         if (row != null)
         int numberOfCells = row.getLastCellNum();
         for(int j=0;j <= numberOfCells;j++)
                                  HSSFCell cell = row.getCell((short)j);
         short cellNumber = cell.getCellNum();
         if(cell!=null)
         if(cellNumber == myTradeConstants.scripCode_column_Number)
                                  cell =row.getCell(myTradeConstants.scripCode_column_Number);
                                      scripCode =cell.getStringCellValue();
                                      System.out.println("scripCode:"+scripCode);
                                  else
                                       break;
                        //else
                             System.out.println("rowBreak");
                             break;
              } catch (IOException ioe) {
                   // TODO: handle exception
                   System.out.println("IoException" + ioe.getMessage());
    }

  • How to set ResultSet not null?

    Hello !
    How can I set my ResultSet null? rs.next( ) is null.
    Thanks in advance.

    "...Hey, do you guys have an idea how to apply operator to method getTime() e.g rs.getTime("TimeOut") - rs.getTime("TimeIn")?..."
    It can't be done.
    One thing you should be checking is whether or not the last value returned from the result set was null, using the wasNull() method.
    If you're getting a NPE, it could be that one of the values you think you're getting back from the database is really null.
    Are you sure you want java.sql.Time? Not java.sql.Timestamp?
    Code it like this:
    java.sql.Timestamp timeIn = rs.getTimestamp("TimeIn");
    java.sql.Timestamp.timeOut = rs.getTimestamp("TimeOut");
    long duration = 0L;
    if ((timeIn != null) && (timeOut != null))
        long millisecondsIn = timeIn.getTime();
        long millisecondsOut = timeOut.getTime();
        duration = millisecondsOut - millisecondsIn;
        assert (duration >= 0L);
    }MOD

  • Null check

    I have a basic question on good programming practice.
    If i have a method that returns an object which will be used
    by the callee method.
    Is it better to check for the null return value in the called method or putting the check in the callee method.Please let me know if both are same or if in some process we can optimize the performance.

    It would depend on the situation. What's your situation like?
    For some methods, it's legitimate to return null. For such a method, the caller will need to accept a null return value. Very often, this is not a problem a no null check is needed. If the caller wants to call a method in the returned object -- this is considered poor practice, talking to a stranger or breaking the Law of Demeter -- but if, then it needs to do a null check first.
    Other methods are specified not to return null. For such methods, you may place an assert statement either inside the method before returning, or in the caller after the call, or both. Then, once your program is debugged and running fine, you optimize performance by disabling assertions. If the method is called from many locations, you may prefer to have the assert statement inside the method. On the other hand, now you will understand why some people frown on having multiple return statements in a method. :-)
    This is definitely not all there is to say. I hope it helped a bit anyway.

  • Empty resultset even though it shouldn't be empty

    Dear experts,
    today i did experience a behaviour of hana that i cannot understand.
    In order to enable you to reenact the phenomenon i created the following demo code:
    ######################### PREPERATION
    -- creating a copy of a sap demo content table
    create column table "SAP_HANA_DEMO"."sap.hana.democontent.epm.data::EPM.MasterData.Addresses_TEST"
    like "SAP_HANA_DEMO"."sap.hana.democontent.epm.data::EPM.MasterData.Addresses" with data;
    -- set two columns to null
    Update "SAP_HANA_DEMO"."sap.hana.democontent.epm.data::EPM.MasterData.Addresses_TEST"
    set CITY = NULL;
    Update "SAP_HANA_DEMO"."sap.hana.democontent.epm.data::EPM.MasterData.Addresses_TEST"
    set POSTALCODE = NULL;
    ######################### / PREPERATION
    ######################### INITIAL
    -- returns an empty resultset (initial version)
    select col from (
    select 'CITY' as col, count(*) i from "SAP_HANA_DEMO"."sap.hana.democontent.epm.data::EPM.MasterData.Addresses_TEST" where CITY is not NULL union all
    select 'POSTALCODE', count(*) from "SAP_HANA_DEMO"."sap.hana.democontent.epm.data::EPM.MasterData.Addresses_TEST" where POSTALCODE is not NULL
    ) where i = 0;
    ######################### / INITIAL
    ######################### ALTERED VERSIONS
    -- returns the expected resultset (outer select contains i)
    select col, i from (
    select 'CITY' as col, count(*) i from "SAP_HANA_DEMO"."sap.hana.democontent.epm.data::EPM.MasterData.Addresses_TEST" where CITY is not NULL union all
    select 'POSTALCODE', count(*) from "SAP_HANA_DEMO"."sap.hana.democontent.epm.data::EPM.MasterData.Addresses_TEST" where POSTALCODE is not NULL
    ) where i = 0;
    -- returns the expected resultset (check for "is null")
    select col from (
    select 'CITY' as col, count(*) i from "SAP_HANA_DEMO"."sap.hana.democontent.epm.data::EPM.MasterData.Addresses_TEST" where CITY is NULL union all
    select 'POSTALCODE', count(*) from "SAP_HANA_DEMO"."sap.hana.democontent.epm.data::EPM.MasterData.Addresses_TEST" where POSTALCODE is NULL
    ) where i = (select count(*) from "SAP_HANA_DEMO"."sap.hana.democontent.epm.data::EPM.MasterData.Addresses_TEST");
    -- returns the expected resultset (now without where)
    select col from (
    select 'CITY' as col, count(CITY) i from "SAP_HANA_DEMO"."sap.hana.democontent.epm.data::EPM.MasterData.Addresses_TEST" union all
    select 'POSTALCODE', count(POSTALCODE) from "SAP_HANA_DEMO"."sap.hana.democontent.epm.data::EPM.MasterData.Addresses_TEST"
    ) where i = 0
    ######################### ALTERED VERSIONS
    The question is why does the initial statement return an empty resultset?
    And please consider that the initial version works just fine under rev68 (resultset is not empty), but returns an empty resultset when being executed on a rev70 system.
    Many thanks in advance for your feedback.

    Dear experts,
    today i did experience a behaviour of hana that i cannot understand.
    In order to enable you to reenact the phenomenon i created the following demo code:
    ######################### PREPERATION
    -- creating a copy of a sap demo content table
    create column table "SAP_HANA_DEMO"."sap.hana.democontent.epm.data::EPM.MasterData.Addresses_TEST"
    like "SAP_HANA_DEMO"."sap.hana.democontent.epm.data::EPM.MasterData.Addresses" with data;
    -- set two columns to null
    Update "SAP_HANA_DEMO"."sap.hana.democontent.epm.data::EPM.MasterData.Addresses_TEST"
    set CITY = NULL;
    Update "SAP_HANA_DEMO"."sap.hana.democontent.epm.data::EPM.MasterData.Addresses_TEST"
    set POSTALCODE = NULL;
    ######################### / PREPERATION
    ######################### INITIAL
    -- returns an empty resultset (initial version)
    select col from (
    select 'CITY' as col, count(*) i from "SAP_HANA_DEMO"."sap.hana.democontent.epm.data::EPM.MasterData.Addresses_TEST" where CITY is not NULL union all
    select 'POSTALCODE', count(*) from "SAP_HANA_DEMO"."sap.hana.democontent.epm.data::EPM.MasterData.Addresses_TEST" where POSTALCODE is not NULL
    ) where i = 0;
    ######################### / INITIAL
    ######################### ALTERED VERSIONS
    -- returns the expected resultset (outer select contains i)
    select col, i from (
    select 'CITY' as col, count(*) i from "SAP_HANA_DEMO"."sap.hana.democontent.epm.data::EPM.MasterData.Addresses_TEST" where CITY is not NULL union all
    select 'POSTALCODE', count(*) from "SAP_HANA_DEMO"."sap.hana.democontent.epm.data::EPM.MasterData.Addresses_TEST" where POSTALCODE is not NULL
    ) where i = 0;
    -- returns the expected resultset (check for "is null")
    select col from (
    select 'CITY' as col, count(*) i from "SAP_HANA_DEMO"."sap.hana.democontent.epm.data::EPM.MasterData.Addresses_TEST" where CITY is NULL union all
    select 'POSTALCODE', count(*) from "SAP_HANA_DEMO"."sap.hana.democontent.epm.data::EPM.MasterData.Addresses_TEST" where POSTALCODE is NULL
    ) where i = (select count(*) from "SAP_HANA_DEMO"."sap.hana.democontent.epm.data::EPM.MasterData.Addresses_TEST");
    -- returns the expected resultset (now without where)
    select col from (
    select 'CITY' as col, count(CITY) i from "SAP_HANA_DEMO"."sap.hana.democontent.epm.data::EPM.MasterData.Addresses_TEST" union all
    select 'POSTALCODE', count(POSTALCODE) from "SAP_HANA_DEMO"."sap.hana.democontent.epm.data::EPM.MasterData.Addresses_TEST"
    ) where i = 0
    ######################### ALTERED VERSIONS
    The question is why does the initial statement return an empty resultset?
    And please consider that the initial version works just fine under rev68 (resultset is not empty), but returns an empty resultset when being executed on a rev70 system.
    Many thanks in advance for your feedback.

  • Insufficient privilege: Not authorized at ptime/query/checker/query_check.cc on hdbsequence

    Hi All,
    I am currently trying to create a table (TOPIC) and a sequence (SEQ_TOPIC_ID) in HCP, and a XSJS service on top of it to insert a entry to the table.
    In my XS project, I placed a TOPIC.hdbtable and SEQ_TOPIC_ID.hdbsequence in it. Both table and sequence are generated correctly in my trial account schema in the hana db.
    Then,in order to grant the access to the table and sequence , I also placed a file model_access.hdbrole in the project folder.
    The content looks like follow:
    role i065831trial.bubuwork.TopicCenter::model_access {
        application privilege: i065831trial.bubuwork.TopicCenter::Basic;
        sql object i065831trial.bubuwork.TopicCenter::TOPIC : SELECT,INSERT;
        sql object i065831trial.bubuwork.TopicCenter::SEQ_TOPIC_ID : SELECT, DROP;
    The issue is, when I call the XSJS service from the web url, I will facing below error:
    Error while executing query: [dberror(Connection.prepareStatement): 258 - insufficient privilege: Not authorized at ptime/query/checker/query_check.cc:2547]
    the role has been granted to my account, and I am able to insert to the table TOPIC without sequence with above role setting, but If I try to read the SEQ_TOPIC_ID, an insufficient privilege will shown up.
    My question is: Is following line correct to grant the privilege to a role for sequence ? It does not seem to work for sequence  !
    sql object i065831trial.bubuwork.TopicCenter::SEQ_TOPIC_ID : SELECT, DROP;
    Thanks very much!

    Thanks Thomas for your reply, firstly I tried to embed my sequence in the insert SQL, as the problem happened. I pulled out the sequence into a single query string, like blow:
    var select_topic_next_val = "select \"i065831trial.bubuwork.TopicCenter::SEQ_TOPIC_ID\".nextval as seqid from dummy";
    function close(closables) {
        var closable; 
        var i; 
        for (i = 0; i < closables.length; i++) { 
                  closable = closables[i]; 
                  if(closable) { 
                            closable.close(); 
    function insertTopic(xargs){
        var connection = $.db.getConnection(); 
        var statement = null;
        var resultSet = null;
        try{
            //get next sequence id
            statement = connection.prepareStatement(select_topic_next_val);
            resultSet = statement.executeQuery();
            while(resultSet.next()){
                var seqId = resultSet.getString(1);
                break;
    //        statement = connection.prepareStatement(insert_topic_sql);
    //        statement.setString(1,seqId);
    //        statement.setString(2,xargs.owner);
    //        statement.setString(3,xargs.approver);
    //        statement.setString(4,xargs.name);
    //        statement.setString(5,xargs.status);
    //        statement.setString(6,xargs.description);
    //        //statement.setTimestamp(6,xargs.lastModify);
    //        statement.setTimestamp(7,null);
    //        statement.setDate(8,xargs.begda);
    //        statement.setDate(9,xargs.endda);
    //        statement.setString(10,xargs.keyword);
    //        statement.executeUpdate();
        }finally { 
            close([resultSet, statement, connection]); 

  • OC4J 9.0.4 migrate to 10.1.3.1 JSP fails using abstract class for ResultSet

    Consider the following JSP code snipet:
    <%
    com.class.SQLDataSource detail = ((com.class.SQLDataSource)request.getAttribute("AcctList"));
    %>
    <%while detail.next()) {detail.getRow();%>
    <tr ...>
    <td ...><%= detail.getString("ACCT") %></td>
    </tr>
    <%}%>
    blah, blah, blah
    class snipet looks like this:
    public abstarct class SQLDataSource extends serializable {
    private ResultSet resultSet = null;
    private PreparesStatement stmt = null;
    public boolean next() throws SQLException {
    boolean result = getResultSet().next();
    return (result);
    public String getString(String columnName) throws SQLExcpetion {
    return getResultSet().getString(columnName);
    public void execute() throws SQLException {
    -- checks stmt
    -- if null generates resultSet from "AcctList.sql" query
    -- if not null, re-executes as-is stmt for a query only
    protected ResultSet getResultSet() throws SQLException {
    execute(); // see above
    return resultSet;
    The problem:
    <%= detail.getString("ACCT") %> generates a NullPointerException
    Yet, if I add debug statements in the SQLDataSouce class, they conclusively show that resultSet has 1902 rows and I can diplay the contents on these rows (on the console, of course, the JSP still generates a NullPointerException).
    If I "hardcode" the creation of a ResultSet in the JSP, the pages displays properly (not the desired method).
    PLEASE TAKE NOTE: This JSP/Class combination works PERFECTLY in OC4J 9.0.4 using JDeveloper 9.0.5.2. When I deploy the **EXACT SAME** JSP/Class combination in JDeveloper/OC4J 10.1.3.1, I receive the NullPointerException.
    So what this feels like to me (and my VERY limited J2EE experinece) is that the abstract class SQLDataSource has somehow lost/closed/dropped/corrupted resultSet when "returning" to the JSP for display of the contents of resultSet. This is, of course, a laymans explanation of the experienced effect of running this code.
    It makes me wonder if under 10.1.3.1 "something more" must be done so that the (abstract) SQLDataSource class can operate in the same way it did under 9.0.4.
    Last note: this NullPointerException happens whether I deploy to standalone OC4J 10.1.3.1 or if I execute my application withing JDevloper's Embedded OC4J instance.
    Any Assistance on this MOST aggrivating problem would be greatly appreciated.
    Others have yet to solve it in similar posts of mine. Hopefully this more definitive description will help YOU be my personal HERO.
    Ed.

    repost to pique interest

  • Remove null & empty values

    I created a report with multiple fields. I would like to create a generic formula in which it evaluates all the values and if it found a null or empty value it will be replaced by a 'N/A'. I was searching in the forums and I found the following formula
    if  (isnull() or ( ='')) then
           "Display the required text"
    else
    when I tried to use it i had an error that the value must be boolean. Is there is a way where  I can change all the fields as string?? and a assign "N/A"
    or
    how can I assign a "N/A"to a boolean field??
    also  I have approx. 140 fields to evaluate, does the formula can be generic or I will need to create a formula for each variable??
    thanks

    Usually when Crystal runs across a field that is NULL, it immediately stops executing the formula, unless the field is enclosed within IsNull().  However, I'm not sure if that is the case for a parameter being passed to a function.  So, you may be able to create a function like (Formula Workshop -> Create Custom Functions -> Add; basic syntax):
    function DisplayString (inVal as string) as string
    if (isnull(inVal) or (inVal ='')) then
      DisplayString = "N/A"
    else
      DisplayString = inVal
    end if
    If Crystal does stop when passing a NULL value as a parameter, then you could code a similar function (without the isnull()), and check the Convert NULL Database Values to Default option on the File -> Report Options panel.
    You would need to create one such function for each data type that you want to show "N/A" for, and for data types other than string, convert the value to a string when it is not null.
    These functions could then be used in the Display String formula for the field on the report.
    The only other way I can think of achieving this would be to base the report(s) on an SQL Command and convert NULL values to "N/A" there.  It might be a bit easier to do in an SQL Command, but probably not a whole bunch.
    Or, educate your users that when nothing is printed, it means that it's not applicable! 
    HTH,
    Carl

  • IS NOT NULL in order clause

    Hi -
    It is not allowed to have IS NOT NULL in order by clause, isn't it? When order by clause is being formed dynamically, is there anyway to check for not nulls in any column to be used for order by clause? Thanks,

    If we have order by C1, C2, C3, then .. it is not the same as just C2 and C3 - is it?No, results depend upon content of result set.
    SQL> drop table nulls_ob;
    Table dropped.
    SQL> create table nulls_ob (id1 number, id2 number, id3 number);
    Table created.
    SQL> insert into nulls_ob values(null,100,null);
    1 row created.
    SQL> insert into nulls_ob values(null,110,null);
    1 row created.
    SQL> insert into nulls_ob values(null,null,100);
    1 row created.
    SQL> insert into nulls_ob values(null,null,120);
    1 row created.
    SQL> insert into nulls_ob values(null,90,100);
    1 row created.
    SQL> commit;
    Commit complete.
    SQL> select * from nulls_ob order by 1,2,3;
           ID1       ID2          ID3
                 90          100
                100
                110
                        100
                        120
    SQL> insert into nulls_ob values(70,110,null);
    1 row created.
    SQL> insert into nulls_ob values(90,null,100);
    1 row created.
    SQL> insert into nulls_ob values(80,90,100);
    1 row created.
    SQL> commit;
    Commit complete.
    SQL> select * from nulls_ob order by 1,2,3;
           ID1       ID2          ID3
         70       110
         80        90          100
         90               100
                 90          100
                100
                110
                        100
                        120
    8 rows selected.
    SQL> select * from nulls_ob order by   2,3;
           ID1       ID2          ID3
         80        90          100
                 90          100
                100
                110
         70       110
                        100
         90               100
                        120
    8 rows selected.

  • Check for empty session variable

    Hey there we're making a login for our jsp web application.
    The login allready works and so does the log out but now we want to make a check to make it impossible to login with names that are not in the database.
    So what basicly happens is as follows...
    Login reads the database info:
    while (rs.next()) {
         if (request.getParameter("username").equals(rs.getString("username")) && request.getParameter("password").equals(rs.getString("password"))){
              session.setAttribute("username", rs.getString("username"));
              session.setAttribute("firstname", rs.getString("first_name"));
              session.setAttribute("lastname", rs.getString("last_name"));
    }but when you enter invalid information teh session variabe "lastname" for example should read null. Now we want to make a check for this null value, which should look something like this:
    if(session.getAttribute("username").equals(null)){
         response.setStatus(301);
         response.setHeader("Location", "/index.jsp");
    } else {
         response.setStatus(301);
         response.setHeader("Location", "/mainmenu.jsp");
    }But this doesnt work, it just logs in with the null values... any1 got a clue??
    edit: im actually looking for something like the isSet command in PHP to give an idea...
    Message was edited by:
    whappit

    Your test for null will always fail, because request.getParameter("username") is NEVER null, in that it exists, even though it contains no data.
    Try .equals(""); instead.

  • Problem Generating a Report by passing a Resultset as a datasource

    I am having troubles generating a report using CR for Eclipse 2.0.
    I used the example that shows how do a simple select SQL query to the database and pass the resultset from the query to the report to generate a report from here: https://www.sdn.sap.com/irj/scn/go/portal/prtroot/docs/library/uuid/201084dc-be66-2b10-64bf-dde4970c9b90
    I used a simple rpt file that simply shows the content of two columns from a table: TXN_TYPE_CD and TXN_STATUS_CD from a POLICY_TXN table.
    Using the code above, and just modifying it a bit to include my jdbc connection details as well as my select query, I was able to view the report which populated data from my database (Oracle 10g) at runtime of the application.  This test proved positive.
    However, the problem I am having is that I am trying to make this code into a Servlet for use in a Java EE application running on Websphere 6.1.0.17 using JVM 1.5.0_15  64-bit.  Instead of using the DHTML thick client, I export to PDF.  When I do this, the crystal report shows as a PDF, but the data is missing for some reason.  Only the headers for the two db columns are shown.  I don't see any startling differences between the code and am 100% positive that my resultset is being returned with data (I output the data returned in the result set as shown in the code).
    Here is the code I am using:
    public class CrystalReportGeneratorServlet_WOW extends Servlet {
         private static final long serialVersionUID = 768970549082466125L;
         protected HttpSession session;
         private final String EXPORT_FILE = "myExportedReport.pdf";
         private final String CUSTOM_PATH = "/custom/resource/crystalReport/";
         private String REPORT_NAME;
         public void service(HttpServletRequest request, HttpServletResponse response)
                   throws IOException, ServletException {
              Properties loParms = new Properties();
              ResultSet resultSet = null;
              //Obtain current JDBC Connection
              Connection loConn = AppEnvironment.getJDBCConnection();
              Statement statement = null;
              try {
                   REPORT_NAME = "Test.rpt";
                   //Open report
                   ReportClientDocument reportClientDoc = new ReportClientDocument();
                   reportClientDoc.open(SystemConfig.getAppHome() + CUSTOM_PATH + REPORT_NAME, 0);
                   //Create SQL query.    
                   String query = "SELECT \"POLICY_TXN\".\"TXN_TYPE_CD\", \"POLICY_TXN\".\"TXN_STATUS_CD\"" + "FROM   \"POLICY_TXN\"";
                   //Query database and obtain the Resultset that will be pushed into the report.  
                   statement = loConn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
                   //Execute query and return result set.
                   resultSet = statement.executeQuery(query);
                   //Look up existing table in the report to set the datasource for and obtain its alias.  This table must
                   //have the same schema as the Resultset that is being pushed in at runtime.  The table could be created
                   //from a Field Definition File, a Command Object, or regular database table.  As long the Resultset
                   //schema has the same field names and types, then the Resultset can be used as the datasource for the table.
                   String tableAlias = reportClientDoc.getDatabaseController().getDatabase().getTables().getTable(0).getAlias();
                   /////TESTING: OUTPUT contents of resultSet
                   while (resultSet.next()) {
                        System.out.println("TXN_STATUS_CD = " + resultSet.getString("TXN_STATUS_CD"));
                        System.out.println("TXN_TYPE_CD = " + resultSet.getString("TXN_TYPE_CD"));
                   //Push the Java ResultSet into the report.  This will then be the datasource of the report.
                   DatabaseController dbc = reportClientDoc.getDatabaseController();
                   dbc.setDataSource(resultSet, tableAlias , "resultsetTable");
                   //Export to PDF
                   ExportToPDF(reportClientDoc, response);
              catch(ReportSDKException ex) {     
                   System.out.println(ex);
              catch(Exception ex) {
                   System.out.println(ex);               
              } finally {
                   try {
                        resultSet.close();
                   } catch (SQLException e) {
                             e.printStackTrace();
                        } finally {
                             AppEnvironment.returnStatement(statement);
                             AppEnvironment.returnConnection ( loConn ) ;
         private void ExportToPDF(ReportClientDocument rcd, HttpServletResponse response)
              try {
                   ByteArrayInputStream byteArrayInputStream = (ByteArrayInputStream)rcd.getPrintOutputController().export(ReportExportFormat.PDF);
                   rcd.close();
                   writeToBrowser(byteArrayInputStream, response, "application/pdf", EXPORT_FILE);
              catch(ReportSDKException ex) {
                   System.out.println(ex);
              catch(Exception ex) {
                   System.out.println(ex);
         * Utility method that demonstrates how to write an input stream to the server's local file system.
         private void writeToBrowser(ByteArrayInputStream byteArrayInputStream, HttpServletResponse response, String mimetype, String exportFile) throws Exception {
              //Create a byte[] the same size as the exported ByteArrayInputStream.
              byte[] buffer = new byte[byteArrayInputStream.available()];
              int bytesRead = 0;
              try{
                   //Set response headers to indicate mime type and inline file.
                   response.setHeader("Content-disposition", "inline;filename=" + exportFile);
                   response.setContentType(mimetype);
                   //Stream the byte array to the client.
                   while((bytesRead = byteArrayInputStream.read(buffer)) != -1) {
                   response.getOutputStream().write(buffer, 0, bytesRead);
                   //Flush and close the output stream.
                   response.getOutputStream().flush();
                   response.getOutputStream().close();
              } catch (Exception e){
                        e.printStackTrace();
         public static Servlet getInstance()
            return new CrystalReportGeneratorServlet_WOW();
    Any help would greatly be appreciated.

    Actually Uzair I came across this thread in trying to find a resolution to my problem.  I was wondering if you were able to resolve this issue as it appears as though I may have the same problem.
    Thanks.

  • Is null validation not working correctly

    I have an application in which I have created a data entry page. We are using apex version 3.0.1.00.08.
    I have an item whose source is a database column which has a select list associated with it, as I want to show the user that they have not yet picked anything from the select list i have the lov properties set as follows:
    display null = Yes
    null display value = Please select
    I also have a page processing validation to check that the user has entered a value. the code for this validation is as follows:
    if :P1_DATA_ITEM is null then
    return 'This value for this Item must be selected before this record can be saved to the database';
    else
    return null;
    end if;
    However on the save button if but the user not selected a value for P1_DATA_ITEM so it is still showing -- please select -- the validation does not fail and lets the user save the record. This is not the behaviour that I want as I am trying to trap the fact that the user has not selected a value.
    This seems to indicate that Apex thinks P1_DATA_ITEM is not null so i checked session state for this item and it is showing %null%.
    How can I get a select list to indicate that the user has not actually selected a value but also to validate correctly, how do I deal with items when their session state is %null%.
    The only way round this issue that I have found is to use a radio button because it is obvious that the user has not yet selected a value but I would prefer to use a select list as we will need to do the same thing for other fields where a radio button would be impractical. I also need to indicate to the user that they still have to pick a value for this field and if you do not set the proprerty display null to Yes then it looks to the user as though they have selected an item becuse the first value in the select list appears.
    Can anyone advise on this.
    Regards
    Kay

    Hi Kay...
    Patrick wolf came up with this excellent piece of code here on this forum (I'd reference it but I can't find it at the moment.
    Instead of checking for the %null% state of each select list item on every page you can use this application process to do the job for you...
    Create an Application process
    -) Name: APP_Remove_NULLS
    -) Sequence: 0 (should be a number before any of your page level processes)
    -) On submit: After Page Submission - Before Computations and Validations
    BEGIN
        FOR rItem IN
          ( SELECT ITEM_NAME
              FROM APEX_APPLICATION_PAGE_ITEMS
             WHERE APPLICATION_ID   = TO_NUMBER(:APP_ID)
               AND PAGE_ID          = TO_NUMBER(:APP_PAGE_ID)
               AND LOV_DISPLAY_NULL = 'Yes'
               AND LOV_DEFINITION   IS NOT NULL
               AND LOV_NULL_VALUE   IS NULL
        LOOP
            IF V(rItem.ITEM_NAME) = '%null'||'%'
            THEN
                Apex_Util.set_session_state(rItem.ITEM_NAME, NULL);
            END IF;
        END LOOP;
    /* if you have select lists in your page zero items, remove this comment
        FOR rItem IN
          ( SELECT ITEM_NAME
              FROM APEX_APPLICATION_PAGE_ITEMS
             WHERE APPLICATION_ID   = TO_NUMBER(:APP_ID)
               AND PAGE_ID          = 0
               AND LOV_DISPLAY_NULL = 'Yes'
               AND LOV_DEFINITION   IS NOT NULL
               AND LOV_NULL_VALUE   IS NULL
        LOOP
            IF V(rItem.ITEM_NAME) = '%null'||'%'
            THEN
                Apex_Util.set_session_state(rItem.ITEM_NAME, NULL);
            END IF;
        END LOOP;
    END;This is the first thing I do when I create a new application... It removes that whole '%null'||'%' can of worms in one go...
    Gus..

Maybe you are looking for

  • Policy Assignment to AD Groups

    Perhaps I'm going about this the wrong way, but can someone explain if this should work or not? I have ZESM 4.1 IR 1 installed on a Windows 2003 server with a seperate SQL box - all installed and configured fine. Created a user source pointing at AD,

  • XML to ABAP Structure transformation

    Hi SAP,    Can anyone tell how to transform from XML to ABAP structure. The ABAP structure i'm getting in runtime. Please do the needful. Thanks in advance Vinod.

  • Acrobat 9 Trying to open all my PDFs at once

    I've been using Acrobat 9 everyday for a coupel years.  All of a sudden when I try to open a PDF Acrobat9 tries to open seemingly hundreds of PDFs until I get an error that a maximum number of files allowed to be opened has been reached.  Then My com

  • Satellite L450D not responding after installation of camera software

    Hello, I've just this month bought a L450D back from the UK. Yesterday I tried installing Olympus Digital Camera Software but once installed wouldn't work. Olympus site claim is compatible with Windows 7 but I decided to uninstall software. I'm wonde

  • [SOLVED] Cinnamon 2.0.6-2 crashes with pulseaudio-4.0.5

    Hello After yesterdays cinnamon update issue have been solved I've proceeded with full system update only to find Cinnamon crashing again, though error comes from different package this time. After starting X with startx Cinnamon opens up, then pops