同时读取和写入数据到sql server

时间:2011-11-10 09:56:54

标签: c# sql-server

我有一个服务,它连续地将数据写入一个单独的线程进入SQL数据库。如果我试图从同一个表读取相同的服务,因为我已经写入了它,我得到了这个例外:有已经是一个与此命令关联的开放DataReader,必须先关闭它。 那么有人可以帮我如何同时做到这一点吗?

这是我读取数据的代码:

public Collection ReadData(字符串查询)         {

        {

            _result = new Collection<string[]>();
            string[] tempResult;
            SqlDataReader _readerRead;
            using (_command = new SqlCommand(query, _readConnection))
            {
                _readerRead = _command.ExecuteReader();
                while (_readerRead.Read())
                {
                    tempResult = new string[4];
                    tempResult[0] = _reader[0].ToString();
                    tempResult[1] = _reader[1].ToString();
                    tempResult[2] = _reader[2].ToString();
                    tempResult[3] = _reader[3].ToString();
                    _result.Add(tempResult);
                    //Console.WriteLine("Name : {0} Type : {1} Value : {2} timestamp : {3}", _reader[0], _reader[1], _reader[2], _reader[3]);

                }
                if (_readerRead != null)
                {
                    _readerRead.Close();
                }
                _readConnection.Close();
                return _result;

            }
        }
    }

这里是写给它的:

public void WriteData(Collection<TagInfo> tagInfoList)
    {

        int i = 0;
        for (i = 0; i < tagInfoList.Count; i++)
        {
           using( _command = new SqlCommand(insert statement here)
            {
                _command.Parameters.AddWithValue("Name", tagInfoList[i].Name);
                _command.Parameters.AddWithValue("Type", tagInfoList[i].TagType);
                _command.Parameters.AddWithValue("Value", tagInfoList[i].Value);
                _reader = _command.ExecuteReader();
                if (_reader != null)
                {
                    _reader.Close();
                }
            }
        }

    }

2 个答案:

答案 0 :(得分:5)

您的编写器需要与数据库不同的SQLConnection。您不能为两者使用相同的数据库连接。

答案 1 :(得分:1)

虽然可以这样做,但使用单独的连接我会问你为什么需要这样做。

如果您正在向同一服务中的一个表读取和写入数据,则会在一个SQL表上放置不必要的负载,并且根据您打算进行的查询数量,这可能会导致问题。如果您已经拥有此数据(在不同的线程中),为什么不将数据从后台线程传送到您将数据写入数据库所需的位置,并且您不再需要读取数据。

然而......如果没有看到代码/你想要实现的目标,很难给出一个公平的答案。

相关问题