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

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

    }

最佳答案

您需要一个不同的 SQLConnection 到您的编写器的数据库。您不能对两者使用相同的数据库连接。

关于c# - 同时读取和写入数据到sql server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8077697/

相关文章:

c# - XBAP:发布版本中缺少文本

c# - 日期字段中具有可为空值的存储过程

c# - 添加背景图像时,Xamarin android 网格无法正确缩放单元格

c# - 最长的唯一回文

c# - 带有 VSIX 安装程序和 Nuget 包的 Visual Studio 2012 的多项目/解决方案模板

sql-server - 通过 VPN 的 SQL Server 事务复制

sql-server - 获得每月出勤率

sql - 选择时如何忽略某些相似的行

sql - 如何将表的备份复制到主表中?

c# - 在 C# 中更改 ListView 列的字体大小