Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

SQL/MYSQL question 1

Status
Not open for further replies.

Henryas

Programmer
Mar 28, 2005
16
0
0
US
Hi,

How do you programmatically check the existence of a data in a SQL/MYSQL database? I have tried to do the followings, but it does not seem to work:

Code:
string command = "SELECT COUNT(*) FROM table WHERE username = 'DoesNotExist'; 
MySqlCommand cmd = new MySqlCommand(command,connection); 

if(cmd.ExecuteScalar()==null)[green]//does not work[/green] 
{ 
   [green]//Data not found[/green] 
}else 
{ 
   [green]//Data found[/green] 
}

I have also tried casting but my compiler complains about it ...

Code:
if(((int)cmd.ExecuteScalar())==0) 
{ 
  [green]//Data not found[/green] 
}else 
{ 
  [green]//Data found[/green] 
}

So what does "SELECT COUNT(*)" return if data not found?

Thanks.

Henry
 
<<
The Command object provides the capability to return single values using the ExecuteScalar method. The ExecuteScalar method returns as a scalar value the value of the first column of the first row of the result set.
>>
I think you didn't open the Connection.
Here is the code that works with Sql:
Code:
SqlConnection connection =null;
SqlCommand cmd = null;
try
{
SqlConnection connection = new SqlConnection(strConnection);
string command = "SELECT COUNT(*) FROM table WHERE username = 'DoesNotExist'"; 
SqlCommand cmd = new SqlCommand(command,connection); 
cmd.Connection.Open();
Int32 count = (Int32)cmd.ExecuteScalar();
if (count == 0)
 {
  // no records with above critaeria
 }
 else{
  // found records
 }

}
catch(Exception ex)
{
  string sErr = ex.GetType() + ex.Message;
}
obislavu
 
Hello Obislavu,

Thank you for the reply. I did open the connection. I just didn't include it in the my code snipet.

When I tried your suggestion, the following error occurs: "Specified cast is not valid." right at the point where "Int32 count = (Int32)cmd.ExecuteScalar();" is. I am not sure whether it is MySql-specific quirkiness.

My current workaround is by using

Code:
if(cmd.ExecuteScalar().toString().Equals("0"))
{
  [green]//Data not found[/green]
}else
{
  [green]//Data found[/green]
}

It works fine now, but I just don't understand the need to convert it to string.

Henry
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top