473,396 Members | 1,773 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,396 software developers and data experts.

IDataReader Read() methid question

Hello All!
I am going to crazy and feeling myself so stupid but I don't understand such behaviour.
I have code:
public int getNextAgentId()
{
Int32 agent_id = 0;
IDataReader dr = dbap.DBDataReader("SELECT MAX(agent_id) FROM Agents");
if(dr.Read())
{
agent_id = dr.GetInt32(0);
}
dr.Close();
return agent_id + 1;
}

where dpab is an instance of DB abstraction class, hence using IDataReader interface instead of
concrete DB DataReader such as SqlDataReader.

SELECT returns null due to database table is empty and I have
error message "Data is Null. This method or property cannot be called on Null values."
on line agent_id = dr.GetInt32(0);
As I understand in the begining datareader positioned before first reacord and when I call Read method
it should point to first record but why it returns true in conditions when now rows returned from DB?

Any ideas?
Thanks in advance to all.

Regards,
Nodir Gulyamov
Nov 17 '05 #1
5 6974
I had thought and decide to manually catch exception, but exception is System.Data.SqlTypes.SqlNullValueException.
But this type of exception is generated only in case of using SQL Server, but i need some abstract exception to catch
from all database types. Does somebody has any ideas how can i do it?
Gelios wrote:
Hello All!
I am going to crazy and feeling myself so stupid but I don't
understand such behaviour.
I have code:
public int getNextAgentId()
{
Int32 agent_id = 0;
IDataReader dr = dbap.DBDataReader("SELECT MAX(agent_id) FROM Agents");
if(dr.Read())
{
agent_id = dr.GetInt32(0);
}
dr.Close();
return agent_id + 1;
}

where dpab is an instance of DB abstraction class, hence using
IDataReader interface instead of
concrete DB DataReader such as SqlDataReader.

SELECT returns null due to database table is empty and I have
error message "Data is Null. This method or property cannot be called on
Null values."
on line agent_id = dr.GetInt32(0);
As I understand in the begining datareader positioned before first
reacord and when I call Read method
it should point to first record but why it returns true in conditions
when now rows returned from DB?

Any ideas?
Thanks in advance to all.

Regards,
Nodir Gulyamov

Nov 17 '05 #2
Hi Gelios,
Here the developer has IDBDataReader, which is an abstract class instead of
specific SqlDataReader or OdbcDataReader as one will not need to modify the
code if the database end is changed which will directly change the .NET
database client.
Regarding the second question, I am not quite sure, however, selecting max
value from an empty table still should have return some value. Have you
tried running that query through SQL query analyzer ?
best,
Subin Kushle,
GAPS

"Gelios" <ge****@rbcmail.ru> wrote in message
news:d4***********@gavrilo.mtu.ru...
Hello All!
I am going to crazy and feeling myself so stupid but I don't understand such behaviour. I have code:
public int getNextAgentId()
{
Int32 agent_id = 0;
IDataReader dr = dbap.DBDataReader("SELECT MAX(agent_id) FROM Agents");
if(dr.Read())
{
agent_id = dr.GetInt32(0);
}
dr.Close();
return agent_id + 1;
}

where dpab is an instance of DB abstraction class, hence using IDataReader interface instead of concrete DB DataReader such as SqlDataReader.

SELECT returns null due to database table is empty and I have
error message "Data is Null. This method or property cannot be called on Null values." on line agent_id = dr.GetInt32(0);
As I understand in the begining datareader positioned before first reacord and when I call Read method it should point to first record but why it returns true in conditions when now rows returned from DB?
Any ideas?
Thanks in advance to all.

Regards,
Nodir Gulyamov

Nov 17 '05 #3
Hello Subin,
First of all hanks for reply. Please find inline answers.
Hi Gelios,
Here the developer has IDBDataReader, which is an abstract class instead of
specific SqlDataReader or OdbcDataReader as one will not need to modify the
code if the database end is changed which will directly change the .NET
database client. I am not sure what you meant. Who is developer of IDBDataReader?
Below my code of abstraction class (dbap is instance of DBAbstractionProcessor class):

public class DBAbstractionProcessor
{
// implemented DB provider types
public enum DbType
{
SQLServer,
OLEDb,
ODBC
};

private DbType dbtype;
private AbstractDBFactory dbf;
public DBAbstractionProcessor(DbType db_type)
{
this.dbtype = db_type;
}

private void selectDbType()
{
switch(this.dbtype)
{
case DbType.SQLServer:
this.dbf = new SQLServerDb();
break;
case DbType.ODBC:
this.dbf = new OdbcDb();
break;
case DbType.OLEDb:
this.dbf = new OleDb();
break;
}
}

public void init(string dburl)
{
this.selectDbType();
this.dbf.init(dburl);
}

public void init(string dburl, string user, string passwd)
{
this.selectDbType();
this.dbf.init(dburl,user, passwd);
}

public void connect()
{
dbf.connect();
}

public void disconnect()
{
dbf.disconnect();
}

public DataSet DBAPSelectQuery(string cmd)
{
return this.dbf.DBSelectQuery(cmd);
}

public void DBAPInsertQuery(string cmd)
{
this.dbf.DBInsertQuery(cmd);
}

public IDataReader DBDataReader(string query)
{
return this.dbf.DBDataReader(query);
}

}

Factory class which implements factory design pattern:

/// <summary>
/// Factory Design Patterns implementation.
/// At the present time abstraction if MS SQL Server, ODBC and OLEDB
/// interfaces implemented. In case of neccessety, any other interfaces
/// can be easily implemented.
/// </summary>
public abstract class AbstractDBFactory
{
// database url string
protected string url = null;
// database username
protected string username = null;
// database password
protected string password = null;

// simple initialize by url
public void init(string dburl)
{
if(dburl == null)
{
throw(new ArgumentException("Illigal agruments"));
}
this.url = dburl;
}

// full initialize
public void init(string dburl, string user, string pass)
{
this.init(dburl);
this.username = user;
this.password = pass;
}

// clear all settings
public void destroy()
{
this.url = null;
this.username = null;
this.password = null;
}

// abstract methods which implemented by SQLServerDb, OdbcDb and OleDb classes
abstract public void connect();
abstract public void disconnect();
abstract public DataSet DBSelectQuery(string cmd);
abstract public void DBInsertQuery(string cmd);
abstract public IDataReader DBDataReader(string cmd);

}
And SQL Server implementation:
/// <summary>
/// MS SQL Server interface implementation.
/// </summary>
public class SQLServerDb : AbstractDBFactory
{
// connector
private SqlConnection sqlCon;

public override void connect()
{
// if base class which stores url, username and passwords not initilized
// throw exception
if(base.url == null)
{
throw(new ApplicationException("Class is not initialized. Please run init() first."));
}
else
{
//Disable pooling for sql server
if(base.url.IndexOf("Pooling") == -1)
{
base.url += ";Pooling=false";
}
// if username and password properties exists initilize by them otherwise by url
if(base.username != null && base.password != null)
{
this.sqlCon = new SqlConnection(base.url + ";uid=" + base.username + ";pwd=" + base.password);
LoggingProcessor.Info("url uid pwd init");
}
else
{
this.sqlCon = new SqlConnection(base.url);
LoggingProcessor.Info("url - " + base.url);
}
try
{
sqlCon.Open();
}
catch (Exception e)
{
throw new Exception("SQL Server error: " + e.ToString());
}
LoggingProcessor.Info("sql server connection established");
}
}

// simple select query
// returns DataSet
public override DataSet DBSelectQuery(string cmd)
{
DataSet ds = new DataSet();
try
{
if(this.sqlCon.State == ConnectionState.Closed)
{
this.connect();
}
SqlDataAdapter sqlDA = new SqlDataAdapter();
sqlDA.SelectCommand = new SqlCommand(cmd, sqlCon);
sqlDA.Fill(ds);
}
catch (Exception e)
{
throw new Exception("SQL Server error: " + e.ToString());
}
finally
{
sqlCon.Close();
}

return ds;
}

// simple insert query
public override void DBInsertQuery(string cmd)
{
try
{
if(this.sqlCon.State == ConnectionState.Closed)
{
this.connect();
}
SqlCommand sqlCmd = new SqlCommand(cmd, this.sqlCon);
sqlCmd.Prepare();
sqlCmd.ExecuteNonQuery();
}
catch (Exception e)
{
throw new Exception("SQL Server error: " + e.ToString());
}
}

// DBDataReader - provides selection and returns SqlDataReader
public override IDataReader DBDataReader(string cmd)
{
try
{
if(this.sqlCon.State == ConnectionState.Closed)
{
this.connect();
LoggingProcessor.Info("connection is not initialized. initializing...");
}
SqlCommand sqlCmd = new SqlCommand(cmd, this.sqlCon);
LoggingProcessor.Info(cmd);
//sqlCmd.Prepare();
return sqlCmd.ExecuteReader();
}
catch (Exception e)
{
throw new Exception("SQL Server error: " + e.ToString());
}
}

// disconnect
public override void disconnect()
{
if(sqlCon.State != ConnectionState.Closed)
{
try
{
this.sqlCon.Close();
}
catch (Exception e)
{
throw new Exception("SQL Server error: " + e.ToString());
}
}
}

}

Regarding the second question, I am not quite sure, however, selecting max
value from an empty table still should have return some value. Have you
tried running that query through SQL query analyzer ?
I checked in SQL query analyzer and it was return null value.
best,
Subin Kushle,
GAPS

"Gelios" <ge****@rbcmail.ru> wrote in message
news:d4***********@gavrilo.mtu.ru...
Hello All!
I am going to crazy and feeling myself so stupid but I don't understand


such behaviour.
I have code:
public int getNextAgentId()
{
Int32 agent_id = 0;
IDataReader dr = dbap.DBDataReader("SELECT MAX(agent_id) FROM Agents");
if(dr.Read())
{
agent_id = dr.GetInt32(0);
}
dr.Close();
return agent_id + 1;
}

where dpab is an instance of DB abstraction class, hence using IDataReader


interface instead of
concrete DB DataReader such as SqlDataReader.

SELECT returns null due to database table is empty and I have
error message "Data is Null. This method or property cannot be called on


Null values."
on line agent_id = dr.GetInt32(0);
As I understand in the begining datareader positioned before first reacord


and when I call Read method
it should point to first record but why it returns true in conditions when


now rows returned from DB?
Any ideas?
Thanks in advance to all.

Regards,
Nodir Gulyamov


Nov 17 '05 #4
> agent_id = dr.GetInt32(0);

Change to:

if (!dr.IsDBNull(0))
agent_id = dr.GetInt32(0);
else
agent_id = -1;
--
Dave Sexton
dave@www..jwaonline..com
-----------------------------------------------------------------------
"Gelios" <ge****@rbcmail.ru> wrote in message news:d4***********@gavrilo.mtu.ru...
I had thought and decide to manually catch exception, but exception is System.Data.SqlTypes.SqlNullValueException.
But this type of exception is generated only in case of using SQL Server, but i need some abstract exception to catch
from all database types. Does somebody has any ideas how can i do it?
Gelios wrote:
Hello All!
I am going to crazy and feeling myself so stupid but I don't understand such behaviour.
I have code:
public int getNextAgentId()
{
Int32 agent_id = 0;
IDataReader dr = dbap.DBDataReader("SELECT MAX(agent_id) FROM Agents");
if(dr.Read())
{
agent_id = dr.GetInt32(0);
}
dr.Close();
return agent_id + 1;
}

where dpab is an instance of DB abstraction class, hence using IDataReader interface instead of
concrete DB DataReader such as SqlDataReader.

SELECT returns null due to database table is empty and I have
error message "Data is Null. This method or property cannot be called on Null values."
on line agent_id = dr.GetInt32(0);
As I understand in the begining datareader positioned before first reacord and when I call Read method
it should point to first record but why it returns true in conditions when now rows returned from DB?

Any ideas?
Thanks in advance to all.

Regards,
Nodir Gulyamov

Nov 17 '05 #5
Dave wrote:
agent_id = dr.GetInt32(0);

Change to:

if (!dr.IsDBNull(0))
agent_id = dr.GetInt32(0);
else
agent_id = -1;

Thanks Dave!
I understood that IDataReader also implements IDataRecord interface which define IsDbNull method.
Thanks again.
Nov 17 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Vivek Sharma | last post by:
Hi There, can some one please clarify the difference between SQLDataReader and IDataReader? What are the advantages and disadvantages of each? Thanks Vivek
4
by: Mahesh Kumar.R | last post by:
What is the difference between SqlDataReader and IDataReader ...? kindly with small example... Mahesh~
3
by: js | last post by:
Hi, I want to debug the return idatareader, how to print out some fields value? many thanks.
2
by: יוני גולדברג | last post by:
Hi, In few places within my code the business object pass IDataReader to the GUI. Suddenly i noticed that nowhere in the code the IDataReader is being closed. Does the data binding operation...
2
by: Larry R | last post by:
Whenever I try the following, the reader that is returned is always closed. What am I missing ? When I look at the reader in the ExecuteReader, it is fine. THen it gets closed on the returm. ...
0
by: rsdev | last post by:
Hi, I am new to ASP.NET and I am trying to build a CMS application using theBeerHouse SK. I am adapting the Datareader to collect information from an SQL database and send it to an HtmlHeader. ...
2
by: RP | last post by:
I saw a code in a class where IDataReader is used to retrieve result from query, even if only one column is to be retrieved. It uses a CommandObject with ExecuteReader but not using ExecuteScalar....
0
by: Andrus | last post by:
RDLDesigner report designer requires IDataReader for data access. To use it with Linq, I need to convert Linq projection to IDataReader. var db = new NorthwindContext(); var q = from c in...
1
by: srinirocks | last post by:
I am reading an excel file using ADO.Net. In a column, my first value is nothing and the rest of the values are numbers. But when I read values, I am getting all empty strings. If I replace my first...
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: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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...

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.