簡體   English   中英

與C#中此命令錯誤關聯的打開的數據讀取器

[英]An open datareader associated with this command error in C#

我想構建一個簡單的循環來檢查來自SQL Server的傳入數據,將其與文本字段進行比較,並在沒有重復的情況下執行非查詢。

我寫了這段代碼:

try
{
    bool exists = false;
    conn = new SqlConnection(DBConnectionString);

    SqlCommand check_user = new SqlCommand("SELECT usrEmail FROM tblUsers", conn);
    SqlCommand add_user = new SqlCommand("INSERT INTO tblUsers (usrEmail, usrPassword, usrRealname, usrIsowner) VALUES (@email, @pass, @name, @owner)", conn);
    // (I have removed all the paramaters from this code as they are working and irrelevant)
    conn.Open();

    SqlDataReader check = check_user.ExecuteReader();

    while (check.Read())
    {
        if (Convert.ToString(check[0]) == UserEmail.Text)
        {
            MessageBox.Show("The email you entered already exists in the system.");
            exists = true;
            break;
        }
    }

    if (exists == false)
    {
        add_user.ExecuteNonQuery();
    }
    else
    {
        return;
    }
}
catch (Exception ex)
{
    MessageBox.Show("There was a problem uploading data to the database. Please review the seller's details and try again. " + ex.Message);
    return;
}
finally
{
    conn.Close();
}

我使用斷點,發現代碼可以正常運行while循環,但是當它到達ExecuteNonQuery命令時,它返回一條錯誤消息:

已經有一個與此命令相關的打開的數據讀取器,必須首先關閉

我試圖使用check.Close(); 命令,但是當我這樣做時,由於通過理解的原因,它突然卡在重復的電子郵件錯誤消息中。 另外,我嘗試了一個修復程序,其中數據實際上已發送到數據庫(我在SQL Server Management Studio中看到了),但是仍然給出了錯誤消息...甚至更奇怪,因為nonquery命令是LAST在此功能。 如果奏效了,為什么要去抓呢?

我已經在站點上搜索了答案,但是最常見的答案是MARS(我不知道那是什么)或數據集,在這種情況下,我不想使用它們。

這里有一個簡單的解決方案嗎? 我錯過了代碼中的某些內容嗎?

簡單的解決方法是:

using(SqlDataReader check = check_user.ExecuteReader())
{
    while (check.Read())
    {
        if (Convert.ToString(check[0]) == UserEmail.Text)
        {
            MessageBox.Show("The email you entered already exists in the system.");
            exists = true;
            break;
        }
    }
}

也就是說,此代碼存在一些嚴重的問題。

首先,您並不是只想閱讀所有用戶以檢查是否已使用電子郵件地址。 select count(*) from tblUsers where usrEmail = @email很好...

...或沒有,因為有可能發生比賽。 您應該做的是在usrEmail列上添加唯一約束,然后insert into tblUsers ,以捕獲違規情況。 或者,您可以根據需要使用merge

接下來,您真的不需要到處都有數據訪問代碼。 至少將其分解為單獨的類/方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM