Question

I have this code that counts the number of records with the same year and date. But when I run the application it doesn't work. Here is my code:

try
{
    string query = "SELECT * FROM tblOrder WHERE dateTime_coded=@dateTimeNow";

    MySqlCommand cmd = new MySqlCommand(query, con);
    cmd.Parameters.AddWithValue("@dateTimeNow", Convert.ToDateTime(DateTime.Now).ToString("yyyy-MM"));

    MySqlDataReader dr = cmd.ExecuteReader();

    MessageBox.Show("OK");
    con.Open();

    while (dr.Read())
    {
        count++;
    }

    dr.Close();
    con.Close();
}
catch (Exception)
{

}
Was it helpful?

Solution

First you have an empty catch block which makes no sense

Atleast this would have been better

catch (Exception ex)
{
     MessageBox(ex.Message);// you would know if in case it failed
}

Now the problem seems to be

MySqlDataReader dr = cmd.ExecuteReader();

MessageBox.Show("OK");
con.Open(); <--- opening after executing the reader ! 

you should try putting the connection in a using block

using(MySqlConnection con = new MySqlConnection())
{
//your stuff in here
}

Another observation

cmd.Parameters.AddWithValue("@dateTimeNow", Convert.ToDateTime(DateTime.Now).ToString("yyyy-MM"))

DateTime.Now is DateTime no need to Convert it again

OTHER TIPS

A better approach to your problem is through ExecuteScalar (link for SqlServer but it is the same for MySql) and using the COUNT function

using(MySqlConnection con = new MySqlConnection("your_connection_string_here"))
{
        con.Open();
        string query = "SELECT COUNT(*) FROM tblOrder WHERE dateTime_coded=@dateTimeNow";
        using(MySqlCommand cmd = new MySqlCommand(query, con))
        {
            cmd.Parameters.AddWithValue("@dateTimeNow", DateTime.Now.ToString("yyyy-MM");
            int count = (int)cmd.ExecuteScalar();
            Console.WriteLine("There are " + count.ToString() + " records");
        }
}

As you can see, I have removed the try/catch block that is useless here because you don't do anything with the exception. This will stop the program if your query contains a syntax error or you can't establish a connection with the server. So, if a try/catch is really needed depends on your requirements

(Added also the observation on the DateTime.Now from V4Vendetta)

You can SELECT COUNT(*) FROM ... and then use cmd.ExecuteScalar() to retrieve the count returned.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top