" ExecuteReader:连接属性尚未初始化。"

时间:2017-01-06 06:10:17

标签: c# sql

private void btnSave_Click(object sender, EventArgs e)
{
    try
    {
        con = new SqlConnection("Data Source = LENOVO; Initial Catalog = MainData; Integrated Security = True");
        con.Open();

        string CheckID = "select StaffID from PersonsData where StaffID='" + txtStaffID.Text + "'";
        cm = new SqlCommand(CheckID);

        SqlDataReader rdr = null;

        rdr = cm.ExecuteReader();

        if (rdr.Read())
        {
            MessageBox.Show("Company Name Already Exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            txtStaffID.Text = "";
            txtStaffID.Focus();
        }
        else
        {
            byte[] img = null;
            FileStream fs = new FileStream(imgLoc, FileMode.Open, FileAccess.Read);
            BinaryReader br = new BinaryReader(fs);
            img = br.ReadBytes((int)fs.Length);
            string Query = "insert into PersonsData (StaffID, FullName, Email, Address, Picture) values('" + this.txtStaffID.Text + "','" + this.txtFullname.Text + "','" + this.txtEmail.Text + "','" + this.txtAddress.Text + "',@img)";
                    if (con.State != ConnectionState.Open)
                        con.Open();
                    cm = new SqlCommand(Query, con);
                    cm.Parameters.Add(new SqlParameter("@img", img));
                    int x = cm.ExecuteNonQuery();
                    con.Close();
                    MessageBox.Show(x.ToString() + "Successfully Saved!");
                }
            }

            catch (Exception ex)
            {
                con.Close();
                MessageBox.Show(ex.Message);
            }

        }

这是我的代码,我不明白为什么我会收到此错误:

  

ExecuteReader:尚未初始化连接属性。

我正在制作一个保存按钮,如果已经将首先检查Staffid。

4 个答案:

答案 0 :(得分:3)

在执行命令之前,您需要说明要使用哪个连接。在你的情况下,它是:

cm.Connection = con;

请注意,在打开连接后以及创建SqlCommand实例后包含此行代码。

答案 1 :(得分:1)

    con = new SqlConnection("Data Source = LENOVO; Initial Catalog = MainData; Integrated Security = True");
    con.Open();
    string CheckID = "select StaffID from PersonsData where StaffID='" + txtStaffID.Text + "'";
    cm = new SqlCommand(CheckID);
    cm.Connection = con; //Assign connection to command

您没有为阅读器中使用的SqlCommand分配连接

答案 2 :(得分:0)

错误消息足够清楚,你必须通过assignement或通过构造函数为Command分配连接,即:

cm = new SqlCommand(CheckID);
cm.Connection = con; // Should be added
SqlDataReader  rdr = cm.ExecuteReader();

否则你可以使用构造函数来初始化命令,如下所示:

cm = new SqlCommand(CheckID,con);

希望您知道这些事情,因为您在给定代码段的else部分中正确使用了它

答案 3 :(得分:0)

确保将SqlConnection分配给Command-Object。您可以通过构造函数或属性执行此操作:

con = new SqlConnection(//Your Connectionstring)
//assign via Constructor
cm = new SqlCommand(CheckID, con);
//or via Property
cm.Connection = con;
SqlDataReader rdr = null;
rdr = cm.ExecuteReader();

此外,我建议您使用using-block以确保命令和连接在使用后被销毁。

using (var con = new SqlConnection())
{
   using (var cm = new SqlCommand())
   {
   }
}