4

How to check if my table is empty from C#?

I have something like:

public MySqlConnection con;
public MySqlCommand cmd;

 con = new MySqlConnection(GetConnectionString());
 con.Open();
 cmd = new MySqlCommand("SELECT * FROM data;", con);

Or I don't need to call SELECT statement?

2
  • 1
    Select COUNT(*) from data would return the number of rows. If it's 0, then it's empty. It would be faster than what you have (if it does have data) because it would not have to return all the data. Commented May 27, 2012 at 17:15
  • 1
    "select count(*) from mytable" is the answer. "int nRows = System.Convert.ToInt32(cmd.ExecuteScalar())" is how you can execute it. Commented May 27, 2012 at 17:27

4 Answers 4

5

You can use COUNT(*) with no WHERE close and see if exactly how many rows exist with the result.

Or you can do a SELECT (id) FROM tablename with no WHERE clause and if no rows are returned then the table is empty.

Sign up to request clarification or add additional context in comments.

2 Comments

can you give me an example please.
I don't know C# so I can't post a code example. But if you can do basic MySQL queries this should be easy to do.
5

I'll give you an example in C# good luck

public bool checkEmptyTable(){
        try
        {
            MySql.Data.MySqlClient.MySqlCommand com = new MySql.Data.MySqlClient.MySqlCommand();
            conn = new MySql.Data.MySqlClient.MySqlConnection("YOUR CONNECTION");
            com.Connection = conn;
            com.CommandText = "SELECT COUNT(*) from data";

            int result = int.Parse(com.ExecuteScalar().ToString());

            return result == 0; // if result equals zero, then the table is empty
        }
        finally
        {
            conn.Close();
        }
   }

Comments

0

If 'data' might be a big table you would be better with this (where pkdata is your primary key field)

SELECT COUNT(*) FROM data WHERE pkdata = (SELECT pkdata FROM data LIMIT 1);

This will run very quickly whether you have 0 rows in 'data' or millions of rows. Using SELECT with no WHERE or ORDER BY means it just pulls the first row available, LIMIT 1 stops it getting more than 1. Maybe something to look for if you have a program that ran very quickly six months ago but now runs like a dog in treacle!

Comments

-1
SELECT COUNT(*) 
FROM table 
WHERE `col_name` IS NOT NULL

1 Comment

While this code may provide a solution to problem, it is highly recommended that you provide additional context regarding why and/or how this code answers the question. Code only answers typically become useless in the long-run because future viewers experiencing similar problems cannot understand the reasoning behind the solution.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.