Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if mysql table is empty?

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?

like image 297
user123_456 Avatar asked Jan 16 '23 13:01

user123_456


2 Answers

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.

like image 143
John Conde Avatar answered Jan 25 '23 19:01

John Conde


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();
        }
   }
like image 30
Brodie Avatar answered Jan 25 '23 18:01

Brodie