连接没有关闭。连接的当前状态是打开的。错误

时间:2016-10-21 11:38:52

标签: c# asp.net

我在try..catch块中有一组代码,它给出了错误

  

连接未关闭。连接的当前状态是打开的

try
    {
        MainEnqMkey = InsertUpdateDelete.InsertUpdateDeleteCls.InsertUpdateDelete_oracle(HidMode.Value, Convert.ToInt32(HidMKey.Value), "XXCUS.XXACL_PN_AGRMNT_MST", "MKEY", "AM", sb.ToString());

        if (Request.QueryString["Mode"] != "M")
        {
            ObjPriCon.Open();
            OracleCommand ObjPriCmd_seq2 = new OracleCommand("select XXCUS.XXACL_PN_AGRMNT_MST_SEQ.nextval from dual", ObjPriCon); // generating ref no here.
            string strRefNo = Convert.ToString(ObjPriCmd_seq2.ExecuteOracleScalar());

            Response.Write("<script language=javascript> alert('Your Document No is : " + strRefNo.ToString() + "')</script>");

            OracleCommand cmd2 = new OracleCommand("Update XXCUS.XXACL_PN_AGRMNT_MST set DOC_NO = '" + strRefNo.ToString() + "' where MKEY = '" + MainEnqMkey + "'", ObjPriCon); // Updating ref no here

            OracleCommand cmd3 = new OracleCommand("Update xxcus.xxacl_pn_farming_mst set LAST_DOC_NO = '" + txtdocno.Value + "' where project_id = '" + ddlProject.SelectedValue + "' and VILLAGE = '" + ddlVillage.SelectedValue + "' and SURVEY_AREA_7_12 = '" + ddl712.SelectedValue + "' and LEGAL_ENTITY = '" + txtCompName.Value + "' " + 
                                                    " and TALUKA = '" + ddlTaluka.SelectedValue + "'");  // updating doc as last doc no

            cmd2.ExecuteNonQuery();

            cmd3.ExecuteNonQuery();
            ObjPriCon.Close();
        }

        ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Record Saved Successfully');window.location ='Frm_Agreement_Master.aspx?TranType=AM&PView=N&Mode=A&Redirect=oracle&Key=0&Redirect=" + Request.QueryString["Redirect"] + "&userid=" + Request.QueryString["userid"].ToString() + "';", true);
    }
    catch (Exception ex)
    {
        ex.Message.ToString();
    }

ObjPriCon.Open();它会阻止并抛出上述错误。

4 个答案:

答案 0 :(得分:2)

不是打开打开的连接,而是检查它的状态,如

if (ObjPriCon.State != ConnectionState.Open)
{
    ObjPriCon.Open();
}

答案 1 :(得分:1)

您可以使用连接状态使用 hacky way 来解决此问题,但共享一个连接并不是一件好事。连接池是你的朋友。所以你可以重新编写代码:

using(OracleConnection conn = new OracleConnection("connectionString"))
{
     conn.Open();
     //your code
     //using block will automatically close your connection when you are done.
} 

目前您还可以使用 Sql Injection 。使用paramatrized查询

OracleCommand cmd2 = new OracleCommand("Update XXCUS.XXACL_PN_AGRMNT_MST set DOC_NO = @Doc_No  where MKEY =@MKey , conn);

cmd2.Parameters.AddWithValue("@Doc_No", strRefNo.ToString());
cmd2.Parameters.AddWithValue("@Mkey", MainEnqMkey);

cmd2.ExecuteNonQuery();

请注意,OracleCommand不支持命名参数,因此您应该按照与查询相同的顺序定义它们。

答案 2 :(得分:0)

也许你需要有ObjPriCon.Close();在最后一块。如果它进入捕获状态则无法关闭。

答案 3 :(得分:0)

最好写一下finally块并在其中ObjPriCon.close()

try   
{   
   ObjPriCon.Open();   

}    
catch (Exception ex)
{
   throw ex; 
}
finally
{
  ObjPriCon.close();
}