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

vin*_*gri 1 c# sql-server

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

这是我读取数据的代码:

public Collection ReadData(string query){

        {

            _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;

            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

这是写给它的:

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();
                }
            }
        }

    }
Run Code Online (Sandbox Code Playgroud)

Sim*_*hes 5

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