0

If in php we can do something like where $result is some query:

$result = mysql_query("SELECT * FROM student");
if (mysql_num_rows($results) !==0)
{
//do operation.
}  
else 
echo "no data found in databasae";  

What is equivalent to this if I want to do this in C# language?please advise.

4
  • That depends on quite a few factors - what have you tried? What resources have you looked at or researched to accomplish what you're trying to do? Do you have some code that you've tried? Commented Mar 13, 2014 at 1:46
  • depends on typeof($results) Commented Mar 13, 2014 at 1:52
  • @jdphenix I do like MySqlDataReader dataReader = cmd.ExecuteReader(); Then I want if this query return results then do operation, if null then throw error message empty database. Commented Mar 13, 2014 at 1:53
  • @DeveloperGuo the result is just the number of rows return in the databse. I want to check if the database contain the data entered by the users. Commented Mar 13, 2014 at 1:55

5 Answers 5

2

I have Created a full Console application using mysql. In your select query you are querying the whole table which is a bad idea. use limit to get only one result - this should be enough to determine if there are any rows in the table.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql;
using MySql.Data.MySqlClient;


namespace ConsoleApplication29
{
    class Program
    {
        static void Main(string[] args)
        {
            if (AnyRows())
            {
                Console.WriteLine("There are rows in the database");
            }
            else
                Console.WriteLine("no data found in database");

            //This will pause the output so you can view the results. Otherwise you will see the dos screen open then close.
            Console.Read();
        }

        //This is the Methos to call
        public static bool AnyRows()
        {
            string connectionString = "Server=localhost;Database=test;Uid=root;Pwd=yourpassword;";

            //Wrap this is using clause so you don't have to call connection close
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                connection.Open();
                string query  = "select * from mytable limit 1";

                using (MySqlCommand command = new MySqlCommand(query, connection))
                {
                    MySqlDataReader reader = command.ExecuteReader();
                    return reader.HasRows;
                }
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

this solution get my idea. but is it possible get the number of rows return in database in order to check if there's data rather than checking the id?
Sure..I have edited the text. Note: this is using entity framework which is an ORM for c#.
It syays the type or namespace of MyEntity() is not found. any idea?sorry im new in c#.
I have edited the answer to not use entity framework. You will need to install mysql and mysql connector for c#.
1

assuming "results" is of type int

if(results != 0)
{
   //do operation
}
else
{
   Console.WriteLine("..."); //or output elsewhere
}

c# if else

4 Comments

now result will be the number of rows return in mysql. so how to get that number in c#
type in results.GetType() and let me know what type you are working with.
I have edited my question. result is a query result. mysql_num_rows(result) get number of rows in result.
literally type in Console.WriteLine(results.GetType())
1

add a reference to linq, and it gets really easy

var result = SomeDatabaseCall();
if (result.Any()){
    // do something
}

if you want to filter the results even further, you can do that inside the Any

var result = SomeDatabaseCall();
if (result.Any(r => r.ID == SomeID)){ // ID can be replaced with any properties in your return model
    // do something
}

Comments

0

I got the solution. It is actually very simple. BTW thanks for those who helping. This is the solution:

class DBConnect
{
    private MySqlConnection connection;
    private string server;
    private string database;
    private string uid;
    private string password;

    public DBConnect()
    {
        Initialize();
    }

    private void Initialize()
    {
        server = "your_server";
        database = "your_db";
        uid = "usr";
        password = "pwd";
        string connectionString;
        connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";

        connection = new MySqlConnection(connectionString);
    }

    //open connection to database
    private bool OpenConnection()
    {
        try
        {
            connection.Open();
            return true;
        }
        catch (MySqlException ex)
        {
            //When handling errors, you can your application's response based on the error number.
            //The two most common error numbers when connecting are as follows:
            //0: Cannot connect to server.
            //1045: Invalid user name and/or password.
            switch (ex.Number)
            {
                case 0:
                    MessageBox.Show("Cannot connect to server.  Contact administrator");
                    break;

                case 1045:
                    MessageBox.Show("Invalid username/password, please try again");
                    break;
            }
            return false;
        }
    }

    //Close connection
    private bool CloseConnection()
    {
        try
        {
            connection.Close();
            return true;
        }
        catch (MySqlException ex)
        {
            MessageBox.Show(ex.Message);
            return false;
        }
    }  


public void Select()
    {
            string query = "SELECT * FROM table";

            //Open connection
            if (this.OpenConnection() == true)
            {
                //Create Command
                MySqlCommand cmd = new MySqlCommand(query, connection);

                //Create a data reader and Execute the command
                MySqlDataReader dataReader = cmd.ExecuteReader();

                //Read the data in the database

                if (dataReader.HasRows == true)
                {
                    while (dataReader.Read())
                    {
                        //do retrieve data
                    }
                }else
                {
                    MessageBox.Show("There's no recods in the database");
                }
           }
     }
}

2 Comments

@Luke101's solution is much more complete. He is doing things like opening and closing the connection, preparing the command, and closing the data reader. These are all missing from your example.
@CharlieKilian yep. BUt i want to make it simple. My code also act have the open,close and query. Just it is too long to paste it here. However I have edited some. Thanks btw.
0

It's best to use SELECT 1 instead of grabbing unnecessary data from the database to simply check for the existence of rows.

public static bool IsTableEmpty(string tableName)
{
    string cs = "Server=localhost;Database=test;Uid=root;Pwd=sesame;";
    using (var conn = new MySqlConnection(cs))
    {
       conn.Open();
       string sql = string.Format("SELECT 1 FROM {0}", tableName);
       using (var cmd = new MySqlCommand(sql, conn))
       {
          using (var reader = cmd.ExecuteReader())
          {
             return !reader.HasRows;
          }
       }
    }
}

If you want to get the row count, then you'll need something like:

public static int GetTableRowCount(string tableName)
{
    string cs = "Server=localhost;Database=test;Uid=root;Pwd=sesame;";
    using (var conn = new MySqlConnection(cs))
    {
       conn.Open();
       string sql = string.Format("SELECT COUNT(*) FROM {0}", tableName);
       using (var cmd = new MySqlCommand(sql, conn))
       {
          return Convert.ToInt32(cmd.ExecuteScalar());
       }
    }
}

Comments

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.