ExecuteReader:尚未初始化Connection属性

jen*_*eni 40 c# asp.net sql-server-2005

ExecuteReader:尚未初始化Connection属性.

我的编码是

protected void Button2_Click(object sender, EventArgs e)
    {

       SqlConnection conn = new SqlConnection("Data Source=Si-6\\SQLSERVER2005;Initial Catalog=rags;Integrated Security=SSPI");

    SqlDataReader rdr = null;

    try
    {
        // 2. Open the connection
        conn.Open();

        // 3. Pass the connection to a command object
        //SqlCommand cmd = new SqlCommand("select * from Customers", conn);
        SqlCommand cmd=new SqlCommand ("insert into time(project,iteration)
                  values('"+this .name1 .SelectedValue +"','"+this .iteration .SelectedValue +"')");

        //
        // 4. Use the connection
        //

        // get query results
        rdr = cmd.ExecuteReader();

        // print the CustomerID of each record
        while (rdr.Read())
        {
            Console.WriteLine(rdr[0]);
        }
    }
    finally
    {
        // close the reader
        if (rdr != null)
        {
            rdr.Close();
        }

        // 5. Close the connection
        if (conn != null)
        {
            conn.Close();
        }
    }
  }
  }

    }
Run Code Online (Sandbox Code Playgroud)

Gov*_*iya 65

使用它并传递连接对象:

 SqlCommand cmd=new SqlCommand ("insert into time(project,iteration)values('"+this .name1 .SelectedValue +"','"+this .iteration .SelectedValue +"')",conn);
Run Code Online (Sandbox Code Playgroud)


FIr*_*nda 18

之后 SqlCommand cmd=new SqlCommand ("insert into time(project,iteration)values('.... 添加

cmd.Connection = conn;
Run Code Online (Sandbox Code Playgroud)

希望这有帮助


Muh*_*tar 6

你必须为你的命令对象分配连接,比如..

SqlCommand cmd=new SqlCommand ("insert into time(project,iteration)values('"+this .name1 .SelectedValue +"','"+this .iteration .SelectedValue +"')");
cmd.Connection = conn; 
Run Code Online (Sandbox Code Playgroud)