我注意到sqlWrite.ExecuteNonQuery();在几秒钟内执行200次插入查询后,我的代码出错了.我一直以为这using将确保资源得到正确使用,并且不需要做任何事情.这是我第一次遇到这个错误而且我已经用sql/c#处理了近3年不同的事情.
using (SqlConnection varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetails))
{
using (var sqlWrite = new SqlCommand(preparedCommand, varConnection))
{
sqlWrite.Parameters.AddWithValue("@var_agr_fname", var_agr_fname == "" ? (object) DBNull.Value : var_agr_fname);
sqlWrite.ExecuteNonQuery();
}
}
public static SqlConnection sqlConnectOneTime(string varSqlConnectionDetails)
{
var sqlConnection = new SqlConnection(varSqlConnectionDetails);
try
{
sqlConnection.Open();
}
catch
{
DialogResult result = MessageBox.Show(new Form {TopMost = true},
"B??d po??czenia z baz? danych. Czy chcesz spróbowa? nawi?zac po??czenie ponownie?",
"B??d po??czenia (000001)",
MessageBoxButtons.YesNo,
MessageBoxIcon.Stop);
if (result == DialogResult.No)
{
if (Application.MessageLoop)
{
Application.Exit(); // Use this since we are a WinForms app
}
else
{
Environment.Exit(1); // Use this since we are a console app
}
}
else
{
sqlConnection = sqlConnectOneTime(varSqlConnectionDetails);
}
}
return sqlConnection;
}
Run Code Online (Sandbox Code Playgroud)
错误信息: A transport-level error has occurred when sending the request to the server. (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)
考虑到对此错误的建议,我应该使用SqlConnection.ClearAllPools();以确保连接被正确地重置或丢弃.所以我可以使用它,但问题是在何处使用它以及何时使用它?如何知道限制是否会破裂?限制在哪里?在50/150/200?或者我应该在循环中每次使用它?
首先,我要说这段代码太可怕了.您正在将UI与数据连接创建混合在一起.更重要的是,你在一个catch部分内显示一个对话窗口并进行递归调用!这非常混乱,本身可能导致错误和不可预测的行为.并且(原始)格式化使其难以阅读.对于严厉的评论感到抱歉,但您真的应该重新设计此代码.
除此之外,您的代码应该可以正常工作,但如果您收到No process is on the other end of the pipe.错误,则表示您的数据库和/或SQL Server存在问题.看起来它被堵塞了,只是不接受任何更多的连接.如果您在短时间内运行批量插入,请尽可能在一个连接上执行.ClearAllPools是一种在发生错误时恢复的方法,最好找出它是什么而不是掩盖它.就像服用扑热息痛一样,当你的牙齿受伤而且从不去看牙医时.
另一件事是使用多个SqlConnections为每个连接创建单独的事务.这增加了SQL Server的负载,尽管它每秒肯定可以完成数百次以上的事务.
此外,您可以将传输更改为命名管道和TCP以查看它是否更改任何内容.
这两个错误:
向服务器发送请求时发生传输级错误。(提供程序:TCP 提供程序,错误:0 - 现有连接被远程主机强制关闭。)
向服务器发送请求时发生传输级错误。(提供程序:共享内存提供程序,错误:0 - 管道的另一端没有进程。)
与日期时间早于 1900 年的日期时间值插入 SQL 相关。Microsoft 的规则是.. 不要在 SQL 中的 DateTime 值中存储小于 1900 年的 DateTime 值。使用字符串代替...