1

Working with C# and MySQL here (Visual Studio 12 and MySQL workbench 6.1).

This is what I have so far.

string strCheck = "SHOW TABLES LIKE \'emp\'";
MySqlCommand cmd = new MySqlCommand(strCheck, con);
cmd.Prepare();

if (cmd.ExecuteNonQuery() > 0)
{
     Console.WriteLine("exists");
}
else
{
     Console.WriteLine("does not");
}

I have seen many questions here (mostly related to PHP) but they don't seem to be working for me. Also, I don't want a solution where we check if the table has any rows, because the table can be empty, and what I want to know is whether it exists.

Thanks.

5
  • ExecuteNonQuery will return number of rows affected and I think you not affecting any rows in your SQL statement. Try to use Reader. Commented Sep 2, 2014 at 7:56
  • @Reniuz so MySqlCommand.Reader() ? Commented Sep 2, 2014 at 8:01
  • 2
    var reader = cmd.ExecuteReader(); if(reader.HasRows) Console.WriteLine("Exists") or if(reader.Read()) ... Commented Sep 2, 2014 at 8:03
  • @Reniuz doesn't work. Gives a false positive. Commented Sep 2, 2014 at 8:07
  • @Reniuz Update: Changed the query and works with your method. Thanks a lot. Commented Sep 2, 2014 at 8:09

1 Answer 1

3

Try the following SELECT statement:

SELECT EXISTS(
    SELECT
        `TABLE_NAME`
    FROM
        `INFORMATION_SCHEMA`.`TABLES`
    WHERE
        (`TABLE_NAME` = 'emp')
        AND
        (`TABLE_SCHEMA` = 'mydb')
) as `is-exists`;
Sign up to request clarification or add additional context in comments.

6 Comments

Keep in mind: You need MySQL 5.0 to use the INFORMATION_SCHEMA
@KenanZahirovic OP is using Visual Studio 12 and MySQL workbench 6.1. I do really have a doubt, that OP has old database engine.
Thanks for the answer. Do you mind implementing this in the above C# code segment?
I solved the problem. My previous query works but I had to use var reader = cmd.ExecuteReader(); if(reader.HasRows) Console.WriteLine("Exists"). Thanks anyways!
@john Then the accepted answer is not the answer, your comment is the answer
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.