ExecuteScalar problem for null values

M

Manikandan

Hi,
I have a table with following data
Tablename:details

No(varchar) Name(varchar) Updated(Datetime)
1 mm 10/10/2006
2 nn 02/12/2005
3 kk NULL

I'm using executescalar to get the updated values from the table
Sql query is "select updated from details where no='1' and name ='kk'
When execute the above query it is throwing error as "object reference
not set to an instance of an object "

Code as below

string date;
string Query="select updated from details where no='"+ no+"' and
name='"+ name+"'";
SqlCommand Command=new SqlCommand(Query,connection);
date=Command.ExecuteScalar().ToString();
Is it possible to cast a date value to string in execute scalar
method?.
Kindly help me to solve the issue


Manikandan
 
G

Guest

ExecuteScalar returns type Object. So if you get back null, obviously you
cannot call the ToString() method on thin air. Check for null first, then
decide.

Also, you should be using parameterized SQL queries instead of inline
concatenation of a SQL string.
Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top