问题描述
大家好,
我面临一个问题。可能是它非常简单但我无法解决它。
我得到例外:
Hello all,
I am facing one issue. Might be its very simple but i unable to solve it.
I am getting exceptions as :
There is already an open DataReader associated with this Command which must be closed first.
我的代码块是:
My Code block is :
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
bool Ok = false;
dt.OpenCon();
string query = "select MA_Joining_Date from master_applicant where MA_App_Code='" + Session["U_Emp_Code"].ToString() + "'";
SqlDataReader dr = dt.ExecuteReader(query);
while (dr.Read())
{
DateTime date1 = DateTime.Parse(dr["MA_Joining_Date"].ToString());
if (DateTime.Now.AddMonths(-6) < date1)
{
drdwnLeaveType.SelectedValue = "4";
}
}
在同一个按钮上我还放了3个条件,一切正常。
on the same button i put another 3 conditions also, that all are working properly.
double NOD1 = Convert.ToDouble(ViewState["NoOfDays"].ToString());
string qry = "select Status_ID from applicant_leavedetails where App_Code ='" + Session["U_Emp_Code"].ToString() + "' and Status_ID ='0'";
string Status = dt.ExecuteScalar(qry);
if (Status != "")
{
ScriptManager.RegisterStartupScript(Page, GetType(), "key1", "alert('Your previous application is pending');", true);
}
else if (NOD1 == 0)
{
ScriptManager.RegisterStartupScript(Page, GetType(), "key1", "alert('You have to select calculate leave days');", true);
}
else if (NOD1 <= 2 && drdwnLeaveType.SelectedIndex == 1)
{
ScriptManager.RegisterStartupScript(Page, GetType(), "key1", "alert('Please select CL Leave bellow that 2 days');", true);
Ok = false;
}
但不是条件不能正常工作。我该怎么办?
but not while condition is not working properly. what should i do??
推荐答案
string query = "select MA_Joining_Date from master_applicant where MA_App_Code='" + Session["U_Emp_Code"].ToString() + "'";
using (SqlDataReader dr = dt.ExecuteReader(query))
{
while (dr.Read())
{
DateTime date1 = DateTime.Parse(dr["MA_Joining_Date"].ToString());
if (DateTime.Now.AddMonths(-6) < date1)
{
drdwnLeaveType.SelectedValue = "4";
}
}
}
这将关闭,处理并从范围中删除SqlDataReader,以免意外再次使用。
请为此,请不要那样做SQL!不要连接字符串以构建SQL命令。它让您对意外或故意的SQL注入攻击持开放态度,这可能会破坏您的整个数据库。请改用参数化查询。
This will Close, Dispose and remove the SqlDataReader from scope so it can't be accidentally used again.
And please, for your own sake, don't do SQL like that! Do not concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead.
这篇关于如何删除此例外?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!