简体   繁体   English

ExecuteNonQuery:连接属性尚未初始化

[英]ExecuteNonQuery: Connection property has not been initialized

I'm receiving an error that says that the connection property has not been initialized (see https://imgur.com/CTHIabz ). 我收到一条错误消息,指出连接属性尚未初始化(请参阅https://imgur.com/CTHIabz )。 This is confusing, as it is the same code that is in other methods that work just fine. 这很令人困惑,因为它与其他方法中的相同代码正常工作一样。 Here is the code: 这是代码:

public bool AddBirthday(string full_name, string month, int day, int year)
{
    if (!string.IsNullOrWhiteSpace(full_name) && month.ToString() != "" && day.ToString() != "" && year.ToString() != "")
    {
        // all required fields were filled out
        // determine which month
        values = birthdayMonths.Where(v => v.Value == month).ToList();

        using (OleDbConnection dbConn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\qbcdb.mdb"))
        {
            dbConn.Open();

            using (cmd = new OleDbCommand("INSERT INTO birthdays (full_name, birthday_month, birthday_day, birthday_year) VALUES (@full_name, @birthday_month, @birthday_day, @birthday_year)"))
            {
                foreach (KeyValuePair<int, string> key in values)
                {
                    if (key.Value != "")
                    {
                        try
                        {
                           cmd.Parameters.AddWithValue("@full_name", full_name);
                           cmd.Parameters.AddWithValue("@birthday_month", key.Value);
                           cmd.Parameters.AddWithValue("@birthday_day", day);
                           cmd.Parameters.AddWithValue("@birthday_year", year);

                           if (cmd.ExecuteNonQuery() > 0)
                           {
                               return true;
                           } 
                        }
                        catch (Exception e)
                        {
                           MessageBox.Show(e.Message);
                        }
                    }
                    else
                    {
                        MessageBox.Show("No values were given.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
               }
            }

            dbConn.Close();
         }
     }

     return false; 
}

I've gone over the code and checked to make sure the database was in the right location and everything else I could think of. 我检查了代码,并检查以确保数据库位于正确的位置以及其他所有我能想到的位置。 I'm confused on why this work would on another method that uses the same code (almost) when it comes to the database query and binds it to a dvg. 对于数据库查询并将其绑定到dvg时,为什么在使用相同代码(几乎)的另一种方法上进行这项工作,我感到困惑。

Any help would be appreciated. 任何帮助,将不胜感激。

Thanks! 谢谢!

Oh btw, it inserts selected values from a listboxes, as demonstrated here: 哦,顺便说一句,它会从列表框中插入选定的值,如此处所示:

insertBirthday.Click += (senders, argss) =>
{
     if (btd.AddBirthday(name.Text, birthdays.SelectedItem.ToString(), Convert.ToInt32(dayListBox.SelectedItem.ToString()),
         Convert.ToInt32(yearListBox.SelectedItem.ToString())))
     {
         MessageBox.Show("Birthday Added Successfully", "Success", MessageBoxButtons.OK);
      }
};

将此构造函数用于OleDbCommandOleDbCommand构造函数(字符串,OleDbConnection)

You haven't assigned the connection to your OleDbCommand. 您尚未将连接分配给OleDbCommand。 There are two ways you could to this: 有两种方法可以实现:

cmd.Connection = dbConn;

or in the constructor: 或在构造函数中:

using (cmd = new OleDbCommand(sql, dbConn)) { ... }

It's also good practice not to open your connection until you are going to use it, ie right before cmd.ExecuteNonQuery() . 在您要使用连接之前,也就是cmd.ExecuteNonQuery()之前,不要打开连接。 Since you are using a using block, you also don't need to close the connection, that will be taken care of for you, but it's probably not hurting anything. 由于您使用的是using块,因此您也不需要关闭连接,这将为您解决,但可能不会造成任何伤害。

I recommend separating your database code from your UI code and validation logic (showing MessageBox and checking values) into a separate "repository" class. 我建议将数据库代码与UI代码和验证逻辑(显示MessageBox和检查值)分开,放入单独的“存储库”类中。 All of the data necessary to perform the operation should also be passed in as a parameter to your database code so that you don't have any confusing issues where those values aren't being set somewhere else. 执行该操作所需的所有数据也应作为参数传递到数据库代码中,这样就不会在未在其他位置设置这些值的情况下出现任何令人困惑的问题。 Calculate the values to insert before calling the method and then pass those as parameters. 在调用方法之前计算要插入的值,然后将其作为参数传递。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM