Click here to Skip to main content
15,905,616 members
Please Sign up or sign in to vote.
1.50/5 (2 votes)
See more:
I m getting the following error when i execute my code...please suggest..
Error-Specified cast is not valid
C#
long count;
string myScalarQuery = "SHOW TABLES LIKE 'table1';";
MySqlCommand myCommand = new MySqlCommand(myScalarQuery, conn);
conn.Open();
count = (long)myCommand.ExecuteScalar();
conn.Close();
if (count == 0)
  Response.Write("no such table exists");
else
  Response.Write("  "+ count );
Posted
Updated 14-Mar-15 23:28pm
v2

1 solution

ExecuteScalar[^] returns the 'first column of the first row' - why do you think it is a long?

[UPDATE AS RESPONSE TO OP COMMENT]
To see only how many records a query returns use ExecuteNonQuery[^] - it has a integer return value, the number of rows.
 
Share this answer
 
v2
Comments
Somesh Dhal 15-Mar-15 5:33am    
i wanna see if it results any rows so that i can i can check whether a table with the same name already exists..how to solve this?
Kornfeld Eliyahu Peter 15-Mar-15 5:41am    
See updated solution...
Somesh Dhal 15-Mar-15 7:35am    
i changed the code to following...

int count;
string myScalarQuery = "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'test' AND table_name = 'login';";

MySqlCommand myCommand = new MySqlCommand(myScalarQuery, conn);
conn.Open();
count = (int)myCommand.ExecuteNonQuery();
conn.Close();
if (count == 0)
Response.Write("no such table exists");
else
Response.Write(" "+ count );
still i i always get the error saying no such table exists even if the table 'login' exists..what to do?
Kornfeld Eliyahu Peter 15-Mar-15 7:42am    
Why did you changed you query? You current query using aggregate function and has a totally different behavior!!!
A select count(*) from table will always return exactly 1 row regardless it found something or not, the only different is the value of count(*) - 0 or more!
Somesh Dhal 15-Mar-15 7:49am    
int count;
string myScalarQuery = "SHOW TABLES LIKE 'table1';";

MySqlCommand myCommand = new MySqlCommand(myScalarQuery, conn);
conn.Open();
count = (int)myCommand.ExecuteNonQuery();
conn.Close();
if (count == 0)
Response.Write("no such table exists");
else
Response.Write(" "+ count );
even this gives the same result "no such table exists" even if it exists...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900