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.
    – Renatas M.
    Sep 2, 2014 at 7:56
  • @Reniuz so MySqlCommand.Reader() ?
    – john
    Sep 2, 2014 at 8:01
  • 2
    var reader = cmd.ExecuteReader(); if(reader.HasRows) Console.WriteLine("Exists") or if(reader.Read()) ...
    – Renatas M.
    Sep 2, 2014 at 8:03
  • @Reniuz doesn't work. Gives a false positive.
    – john
    Sep 2, 2014 at 8:07
  • @Reniuz Update: Changed the query and works with your method. Thanks a lot.
    – john
    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`;
6
  • Keep in mind: You need MySQL 5.0 to use the INFORMATION_SCHEMA Sep 2, 2014 at 7:54
  • @KenanZahirovic OP is using Visual Studio 12 and MySQL workbench 6.1. I do really have a doubt, that OP has old database engine.
    – BlitZ
    Sep 2, 2014 at 7:58
  • Thanks for the answer. Do you mind implementing this in the above C# code segment?
    – john
    Sep 2, 2014 at 8:06
  • 3
    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
    Sep 2, 2014 at 8:10
  • 1
    @john Then the accepted answer is not the answer, your comment is the answer Sep 26, 2019 at 16:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.