gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 19:26:41 34 4
gpt4 key购买 nike

我有一个服务,它在一个单独的线程中不断地将数据写入 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/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com