开发者

MySQL Query with MySQLParameters in C#

I am currently developing an Application for Windows using MySQL and C#. I have the following code:

    private void cboCategories_SelectedIndexChanged(object sender, EventArgs e)
            {
                DatabaseWork dbase = new DatabaseWork();
                try
                {
                    dbase.openConnection();
                    string query = "SELECT * FROM budgetcategory WHERE budc_userID=@userID AND budc_category=@category";
                    MySqlCommand cmd = new MySqlC开发者_JAVA技巧ommand("", dbase.conn);

                    cmd.CommandText = query;
                    cmd.Parameters.AddWithValue("@userID", userID);
                    cmd.Parameters.AddWithValue("@category", cboCategories.SelectedItem.ToString());

                    MySqlDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        setCatId(reader.GetString("budc_category_id"));
                        Console.WriteLine("Category ID: " + getCatId());
                    }
                }
                catch (MySqlException ex)
                {
                    Console.WriteLine("Cat Error: " + ex.Message);
                }
                finally
                {
                    dbase.closeConnection();
                }
}

For some reason when I debug the code it never goes into the while loop as if nothing was ever returned from the database. But I know there should be something in there.

Thanks for any help you can provide


Just trying to help you debug a little:

Try reducing these three lines:

string query = "SELECT * FROM budgetcategory WHERE budc_userID=@userID AND budc_category=@category";
MySqlCommand cmd = new MySqlCommand("", dbase.conn);
cmd.CommandText = query;

to just:

string query = "SELECT * FROM budgetcategory WHERE budc_userID=@userID AND budc_category=@category";
MySqlCommand cmd = new MySqlCommand(query, dbase.conn);

Now put a breakpoint on those lines that add the parameters, and make sure that userID and especially cboCategories.SelectedItem.ToString() have the values that you expect.

Also, can you confirm that no exception is thrown?

If this is not the case run the query, with those exact values directly against the database and confirm that something is returned.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜