已经有一个与此命令关联的开放式数据读取器,必须先关闭它

时间:2014-10-08 11:03:11

标签: c# asp.net

我正在尝试以二进制格式将图像文件保存到db中。并检索这些二进制文件并在我的网页上显示图像。使用下面给出的代码时,已生成一个错误。请帮帮我。

public partial class Default3 : System.Web.UI.Page
{
    static SqlConnection con = new SqlConnection(@"connectionString");
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            filldropdown();
        }
    }

    private void filldropdown()
    {
        SqlCommand cmd = new SqlCommand("Select EmpID from Tbl_Emp", con);
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        SqlDataReader dr = cmd.ExecuteReader();
        TextBox3.Items.Clear();
        if (dr.HasRows)
        {

            while (dr.Read())
            {
                TextBox3.Items.Add(dr["EmpID"].ToString());
            }
        }
        con.Close();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlCommand cmd = new SqlCommand("insert into Tbl_Emp values(@id,@name,@image)", con);
        cmd.Parameters.AddWithValue("@id", TextBox1.Text);
        cmd.Parameters.AddWithValue("@name", TextBox2.Text);

        int img = FileUpload1.PostedFile.ContentLength;

        byte[] msdata = new byte[img];

        FileUpload1.PostedFile.InputStream.Read(msdata, 0, img);

        cmd.Parameters.AddWithValue("@image", msdata);

        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        cmd.ExecuteNonQuery();

        con.Close();
        filldropdown();
        Response.Write("Data Saved ....");

    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        SqlCommand cmd = new SqlCommand("select * from Tbl_Emp where EmpID=@id", con);
        cmd.Parameters.AddWithValue("@id", TextBox3.Text);
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        SqlDataReader dr = cmd.ExecuteReader();
        if (dr.HasRows && dr.Read())
        {
            TextBox1.Text = dr["EmpID"].ToString();
            TextBox2.Text = dr["EmpName"].ToString();
            Image1.ImageUrl = "Handler.ashx?EmpID=" + TextBox3.Text;
        }
        else
        {
            Response.Write("Record With This ID Note Found");
        }
    }
}

来源:

<div>
      Enter ID  <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
      Enter Name <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br />
      Enter Pic  <asp:FileUpload ID="FileUpload1" runat="server" /><br />
      <asp:Button ID="Button1" runat="server" Text="Save" onclick="Button1_Click" /><br >
      <asp:Image ID="Image1"  runat="server" Height="137px" Width="130px" /><br /> 
      <asp:DropDownList ID="TextBox3" runat="server">
      </asp:DropDownList>
      <asp:Button ID="Button2" runat="server" Text="Search" onclick="Button2_Click" />

数据表:

enter image description here

4 个答案:

答案 0 :(得分:3)

处理SQL Connections,命令和读取器清理的最佳方法是使用using语句。此外,您根本不需要根据您发布的代码将连接保持为静态字段。这基本上就是我在每个方法中要做的事情

protected void Some_Action(object sender, EventArgs e)
{
    using(SqlConnection con = new SqlConnection(@"connectionString"))
    {
        con.Open();
        using(SqlCommand cmd = new SqlCommand("Query Here", con))
        {
            // Do stuff with the command here like setting Parameters.
            using(SqlDataReader dr = cmd.ExecuteReader())
            {
                // Do stuff with the reader here
            }
        }
    }
}

这将确保即使发生异常也会处理您的Connection,Command和Reader。

答案 1 :(得分:2)

您必须在打开新对象之前关闭它,因为它是运行时对象..

喜欢这个关闭id

 dr.Close();

答案 2 :(得分:2)

这是正确答案。

public partial class Default3 : System.Web.UI.Page
{
    static SqlConnection con = new SqlConnection(@"connectionString");
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            filldropdown();
        }
    }

    private void filldropdown()
    {
        SqlCommand cmd = new SqlCommand("Select EmpID from Tbl_Emp", con);
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        SqlDataReader dr = cmd.ExecuteReader();
        TextBox3.Items.Clear();
        if (dr.HasRows)
        {

            while (dr.Read())
            {
                TextBox3.Items.Add(dr["EmpID"].ToString());
            }
        }
        dr.Close();
        con.Close();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlCommand cmd = new SqlCommand("insert into Tbl_Emp values(@id,@name,@image)", con);
        cmd.Parameters.AddWithValue("@id", TextBox1.Text);
        cmd.Parameters.AddWithValue("@name", TextBox2.Text);

        int img = FileUpload1.PostedFile.ContentLength;

        byte[] msdata = new byte[img];

        FileUpload1.PostedFile.InputStream.Read(msdata, 0, img);

        cmd.Parameters.AddWithValue("@image", msdata);

        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        cmd.ExecuteNonQuery();

        con.Close();
        filldropdown();
        Response.Write("Data Saved ....");

    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        SqlCommand cmd = new SqlCommand("select * from Tbl_Emp where EmpID=@id", con);
        cmd.Parameters.AddWithValue("@id", TextBox3.Text);
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        SqlDataReader dr = cmd.ExecuteReader();
        if (dr.HasRows && dr.Read())
        {
            TextBox1.Text = dr["EmpID"].ToString();
            TextBox2.Text = dr["EmpName"].ToString();
            Image1.ImageUrl = "Handler.ashx?EmpID=" + TextBox3.Text;
        }
        else
        {
            Response.Write("Record With This ID Note Found");
        }
        dr.Close();
    }
}

答案 3 :(得分:0)

最好使用Using自动Dispose您的连接/读者您已打开的内容

喜欢

    using(SqlConnection con=new SqlConnection)
    {
     SqlCommand cmd=new SqlCommand(con,"query")
     ....
    using(SqlDataReader dr=cmd.ExecuteReader()) 
      {        ....
      }
    }

但您可以在现有代码中使用这样的

private void filldropdown()
    {
        SqlCommand cmd = new SqlCommand("Select EmpID from Tbl_Emp", con);
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        SqlDataReader dr = cmd.ExecuteReader();
        TextBox3.Items.Clear();
        if (dr.HasRows)
        {

            while (dr.Read())
            {
                TextBox3.Items.Add(dr["EmpID"].ToString());
            }
        }
        con.Close();
    dr.Close
    }





protected void Button2_Click(object sender, EventArgs e)
    {
        SqlCommand cmd = new SqlCommand("select * from Tbl_Emp where EmpID=@id", con);
        cmd.Parameters.AddWithValue("@id", TextBox3.Text);
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        SqlDataReader dr = cmd.ExecuteReader();
        if (dr.HasRows && dr.Read())
        {
            TextBox1.Text = dr["EmpID"].ToString();
            TextBox2.Text = dr["EmpName"].ToString();
            Image1.ImageUrl = "Handler.ashx?EmpID=" + TextBox3.Text;
        }
        else
        {
            Response.Write("Record With This ID Note Found");
        }
    dr.Close();
    }