0
votes

I want retrieve data from oracle database, below is my code, My sql query has 4 results how can i retrieve 4 result in my label.

Code

OracleConnection con = new OracleConnection(
"Data Source=10.127.240.216/ipcldb;User ID=ipcltos;Password=ipcltos;Unicode=True");   
con.Open();
OracleCommand cmd = new OracleCommand(
"select Initcap(ZZFNAME) ZZFNAME 
from sap_empmst where substr(GBDAT,1,6) = substr(sysdate,1,6) 
and stat2 =3 and werks in('RIGC','IPGC') and plans<99999999 order by persk", con);      
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();     
// int i;
//   for (i = 0; i < 10; i++)
Label1.Text = dr.GetString(0);
con.Dispose();

thanks in advance.

1
With 4 results you mean 4 rows? Which data you get from this result?Soner Gönül

1 Answers

1
votes

The choice to use a Label to show more than one row info is not a good choice. I would suggest to use a ListBox or Combobox or a Multiline TextBox or event a Grid. (all controls that are built to show more than one item)

But your code has other problems.

Here how I would write it (still using a single label)

string cmdText = @"select Initcap(ZZFNAME) ZZFNAME 
                   from sap_empmst 
                   where substr(GBDAT,1,6) = substr(sysdate,1,6) and stat2 =3 
                         and werks in('RIGC','IPGC') 
                         and plans<99999999 
                   order by persk";
using(OracleConnection con = new OracleConnection(.....))
using(OracleCommand cmd = new OracleCommand(cmdText, con))
{
    con.Open();
    using(OracleDataReader dr = cmd.ExecuteReader())
    {
       while(dr.Read())
          Label1.Text += dr.GetString(0);
    }
}

The fix for the single label problem is to build a loop around the reader using the boolean return value of dr.Read() call. Then using += to concatenate the current record value to the previous content of the label

Another important change revolves around the using statement that ensure the proper closing and disposing of the connection, command and reader also in case of exceptions