让我们考虑以下通过odbc驱动程序连接sql server的连接字符串
"Driver={SQL Server Native Client 10.0};Server=xxx.xx.xx.xx,xxxx;Database=mydata;Uid=xx;Pwd=xxxxxx;"
数据库类型:Sql server
驱动程序:sql server-ODBC native client 10.0
提供者类型:System.Data.Odbc
我在其中通过odbc连接执行50个命令......
在连接字符串1中的前50个和连接字符串2中的其余25中。
有
当我执行那些命令时,大约35个命令执行得很好,之后我得到了错误
ERROR [HY000] [Microsoft][SQL Server Native Client 10.0]Unspecified error occurred on SQL Server. Connection may have been terminated by the server.
用于休息之后执行的所有查询和
堆栈跟踪:
at System.Data.Odbc.OdbcConnection.HandleError(OdbcHandle hrHandle, RetCode retcode)
at System.Data.Odbc.OdbcCommand.ExecuteReaderObject(CommandBehavior behavior, String method, Boolean needReader, Object[] methodArguments, SQL_API odbcApiMethod)
at System.Data.Odbc.OdbcCommand.ExecuteReaderObject(CommandBehavior behavior, String method, Boolean needReader)
at System.Data.Odbc.OdbcCommand.ExecuteNonQuery()
at testprovision.CommonDAL.ExecuteNonQuery(String connectionString, CommandType cmdType, String cmdText, OdbcParameter[] commandParameters) in
执行我使用的非查询循环代码是
public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params OdbcParameter[] commandParameters)
{
int val = 0;
OdbcCommand cmd = new OdbcCommand();
try
{
using (OdbcConnection conn = new OdbcConnection(connectionString))
{
CommonCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
conn.Close();
}
}
catch (Exception ex)
{
}
finally
{
cmd.Dispose();
}
return val;
}
我现在要做的就是解决问题
等待您的回复..
答案 0 :(得分:1)
所以你在CommonCommand中打开conn?
在我看来,这是一种不好的做法
在一个地方打开和关闭。
现在如果ExecuteNonQuery();失败它去了Catch并且conn没有关闭。
尝试这种模式
OdbcConnection conn = new OdbcConnection(connectionString);
try
{
conn.Open();
using (OdbcCommand cmd = conn.CreateCommand)
{
// do NOT have CommonCommand open the connection.
// change CommonCommand to not even pass the connection
CommonCommand(cmd, null, cmdType, cmdText, commandParameters);
val = cmd.ExecuteNonQuery();
// cmd.Parameters.Clear();
// don't need to clear or dipose it will do so when it falls out of scope
}
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}