已经有一个与此命令关联的打开的datareader必须先关闭。 C# [英] There is already an open datareader associated with this command which must be closed first. C#

查看:130
本文介绍了已经有一个与此命令关联的打开的datareader必须先关闭。 C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已经有一个与此命令关联的开放式数据加载器必须先关闭







我的代码如下



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



My code as follows

protected void btnsubmit_Click(object sender, EventArgs e)
        {
 try
            {
                String strConnString = ConfigurationManager.ConnectionStrings["IvcSpiderDBConnectionStrings"].ConnectionString;
                SqlConnection con = new SqlConnection(strConnString);
                con.Open();

                SqlCommand check_User_Name = new SqlCommand("SELECT * FROM [master].[settings] WHERE ([year] = @year) and ([batch] = @batch) ", con);

                check_User_Name.Parameters.AddWithValue("@year", txtyear.Text);
                check_User_Name.Parameters.AddWithValue("@batch", txtbatch.Text);
                SqlDataReader dr = check_User_Name.ExecuteReader();

                if (dr.HasRows)
                {
                    ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Please update year or batch and then click update');", true);
                    return;
                }
                else
                { 
                    SqlCommand cmd = new SqlCommand("UPDATE [master].[settings] set year = '" + txtyear.Text.ToString() + "',batch = '" + txtbatch.Text.ToString() + "'", con);
                    cmd.ExecuteNonQuery();
                    ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Records updated ');", true);
                    con.Close();
                    BindData();
                }
                   dr.Close();
            }
            catch (Exception ex)
            {
                Logger log = new Logger();
                log.WriteToErrorLog("Error while updating data", "EXCEPTION", ex.Message.ToString(), "", "");
            }
}





更新文本框中的记录后显示如下错误



已经有一个与此命令关联的开放式数据加载器必须先关闭。



如何解决此错误。



我尝试了什么:



已经有一个与此相关的开放式数据加载器必须先关闭的命令







我的代码如下





After updating record in textbox shows below error as follows

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

how to solve this error.

What I have tried:

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



My code as follows

protected void btnsubmit_Click(object sender, EventArgs e)
        {
 try
            {
                String strConnString = ConfigurationManager.ConnectionStrings["IvcSpiderDBConnectionStrings"].ConnectionString;
                SqlConnection con = new SqlConnection(strConnString);
                con.Open();

                SqlCommand check_User_Name = new SqlCommand("SELECT * FROM [master].[settings] WHERE ([year] = @year) and ([batch] = @batch) ", con);

                check_User_Name.Parameters.AddWithValue("@year", txtyear.Text);
                check_User_Name.Parameters.AddWithValue("@batch", txtbatch.Text);
                SqlDataReader dr = check_User_Name.ExecuteReader();

                if (dr.HasRows)
                {
                    ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Please update year or batch and then click update');", true);
                    return;
                }
                else
                { 
                    SqlCommand cmd = new SqlCommand("UPDATE [master].[settings] set year = '" + txtyear.Text.ToString() + "',batch = '" + txtbatch.Text.ToString() + "'", con);
                    cmd.ExecuteNonQuery();
                    ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Records updated ');", true);
                    con.Close();
                    BindData();
                }
                   dr.Close();
            }
            catch (Exception ex)
            {
                Logger log = new Logger();
                log.WriteToErrorLog("Error while updating data", "EXCEPTION", ex.Message.ToString(), "", "");
            }
}



更新文本框中的记录后显示以下错误如下



已经有一个与此命令关联的打开的datareader必须先关闭。



如何解决此错误。


After updating record in textbox shows below error as follows

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

how to solve this error.

推荐答案

错误消息非常明确:

The error message is pretty explicit:
There is already an open datareader associated with this command which must be closed first.

您在该连接上有一个打开的DataReader,它将保留该命令直到它关闭。在此之前,您无法对同一个Connection对象进行任何操作。



最简单的解决方案是始终使用使用阻止使用COnnection,Command和Adapter对象,以便它们在超出范围时自动关闭和处理:

You have an open DataReader on that connection, which "holds" the command until it is closed. Until then, you can't do anythign to the same Connection object.

The simplest solution is to always use a using block with COnnection, Command, and Adapter objects so that they are automatically closed and disposed when they go out of scope:

using (SqlCommand check_User_Name = new SqlCommand("SELECT * FROM [master].[settings] WHERE ([year] = @year) and ([batch] = @batch) ", con))
    {
    check_User_Name.Parameters.AddWithValue("@year", txtyear.Text);
    check_User_Name.Parameters.AddWithValue("@batch", txtbatch.Text);
    using (SqlDataReader dr = check_User_Name.ExecuteReader())
       {
        if (dr.HasRows)
            {
            ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Please update year or batch and then click update');", true);
            return;
            }
        }
    }
using (SqlCommand cmd = new SqlCommand("...", con))
    {
    cmd.ExecuteNonQuery();
    ...
    }





但是......你还有其他问题。



#你知道参数化查询,那你为什么突然让自己对SQL注入开放?永远不要连接字符串来构建SQL命令。它让您对意外或故意的SQL注入攻击持开放态度,这可能会破坏您的整个数据库。总是使用参数化查询。



连接字符串时会导致问题,因为SQL会收到如下命令:



But ... You have other problems as well.

#You know about parameterised queries so why are you suddenly leaving yourself wide open to SQL injection as well? Never 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. Always use Parameterized queries instead.

When you concatenate strings, you cause problems because SQL receives commands like:

SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood'

就SQL而言,用户添加的引号会终止字符串,并且您会遇到问题。但情况可能更糟。如果我来并改为输入:x'; DROP TABLE MyTable; - 然后SQL收到一个非常不同的命令:

The quote the user added terminates the string as far as SQL is concerned and you get problems. But it could be worse. If I come along and type this instead: "x';DROP TABLE MyTable;--" Then SQL receives a very different command:

SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable;--'

哪个SQL看作三个单独的命令:

Which SQL sees as three separate commands:

SELECT * FROM MyTable WHERE StreetAddress = 'x';

完全有效的SELECT

A perfectly valid SELECT

DROP TABLE MyTable;

完全有效的删除表格通讯和

A perfectly valid "delete the table" command

--'

其他一切都是评论。

所以它确实:选择任何匹配的行,从数据库中删除表,并忽略其他任何内容。



所以总是使用参数化查询!或者准备好经常从备份中恢复数据库。你经常定期备份,不是吗?



如果你只想知道是否存在任何行,为什么要使用DataReader呢?使用

And everything else is a comment.
So it does: selects any matching rows, deletes the table from the DB, and ignores anything else.

So ALWAYS use parameterized queries! Or be prepared to restore your DB from backup frequently. You do take backups regularly, don't you?

And if you only want to know if any rows exist, why use a DataReader at all? Use

SELECT COUNT(*) FROM ...

而不是SELECT查询,而是调用ExecuteScalar - 它返回一个计数而不是实际数据,效率更高。

instead of your SELECT query, and call ExecuteScalar instead - that returns a count instead of the actual data and is a lot more efficient.


这篇关于已经有一个与此命令关联的打开的datareader必须先关闭。 C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆