![](/img/trans.png)
[英]C# reading large excel xlsx and writing data to sql server express database with entity framework performance issues
[英]Reading and writing data into sql server simultaneously
我有一项服务可以将单独线程中的数据连续写入SQL数据库中。现在,如果我试图从同一张表中读取数据,则可以从同一服务中读取数据,因为我已经在向其中写入数据,所以会出现此异常:已经有一个开放与此命令关联的DataReader,必须先关闭。 那么有人可以帮助我如何同时做到这一点吗?
这是我读取数据的代码:
公共集合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。 您不能为两者使用相同的数据库连接。
尽管可以做到,但使用单独的连接,我会质疑为什么需要这样做。
如果要在同一服务中的一个表中读取数据并将数据写入其中,则将不必要的负载放在一个SQL表上,并且取决于要进行的查询数量,这可能会导致问题。 如果您已经拥有此数据(在另一个线程中),那么为什么不将数据从后台线程编组到需要的位置,再将其写入数据库,也就不再需要读取数据了。
但是...。如果不查看代码/要实现的目标,就很难给出合理的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.