C# ASP.NET error: There is already an open datareader associated with this command which must be closed first

C# ASP.NET error: There is already an open datareader associated with this command which must be closed first

我一直收到这个错误

There is already an open datareader associated with this command which must be closed first.

在这行代码:

using (SqlDataReader rd = command.ExecuteReader())

我试图关闭 class 中的所有其他 SqlDataReader,但没有成功。

public int SifreGetir(string pEmail) {
    SqlCommand command = con.CreateCommand();

    command.CommandText = @"SELECT Sifre FROM Kullanici WITH (NOLOCK) WHERE email=@email";

    command.Parameters.Add("@email", SqlDbType.VarChar);
    command.Parameters["@email"].Value = pEmail;

    using (SqlDataReader rd = command.ExecuteReader())
    {
        rd.Read();
        string pass = rd["Sifre"].ToString();
        int p = Convert.ToInt32(pass);

        return p;
    }
}

尝试以下面的格式实现您的代码

using(SqlConnection connection = new SqlConnection("connection string"))
{

    connection.Open();

    using(SqlCommand cmd = new SqlCommand("your sql command", connection))
    {
        using (SqlDataReader reader = cmd.ExecuteReader())
        {
            if (reader != null)
            {
                while (reader.Read())
                {
                    //do something
                }
            }
        } 

    } 

} 

using 语句将确保在 using 块结束时处理对象

您已经为 SQL Reader 使用了 Using 关键字,但是没有什么可以照顾您的命令和连接对象以正确处理它们。我建议尝试通过 Using 关键字处理您的 Connection 和命令两个对象。

string connString = "Data Source=localhost;Integrated " +   "Security=SSPI;Initial Catalog=Northwind;";

using (SqlConnection conn = new SqlConnection(connString))
{
  SqlCommand cmd = new;
  cmd.CommandText = "SELECT ID, Name FROM Customers";

  conn.Open();

  using (SqlDataReader rd = command.ExecuteReader())
    {
        rd.Read();
        string pass = rd["Sifre"].ToString();
        int p = Convert.ToInt32(pass);

        return p;
    }
}

试试这个:

public int SifreGetir(string pEmail) {

            SqlConnection con = new SqlConnection("Your connection string here");
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter();
            DataSet ds = new DataSet();
            SqlCommand command = new SqlCommand(@"SELECT Sifre FROM Kullanici WITH (NOLOCK) WHERE email=@email",con);
            command.CommandType = CommandType.Text;
            command.Parameters.Add("@email", SqlDbType.VarChar).Value = pEmail;

            da.Fill(ds);
            foreach(DataRow dr in ds.Tables[0].Rows)
           {
                string pass = dr["Sifre"].ToString();
                int p = Convert.ToInt32(pass);
                return p;
           }
           con.Close();
        }