【发布时间】:2017-07-10 11:29:00
【问题描述】:
下面的函数旨在确定查询是否会返回任何行。传入的 SQL 是查询。如果出现错误,该函数应返回 false。但是当 SQL =
SELECT TOP 1 [AU_ID]
FROM [dat].[model_80av2_v1_2941]
WHERE [AU_ID] IS NOT NULL AND convert(int, [AU_ID]) <> [AU_ID]
该函数错误地返回 true,因为没有检测到错误。但是在 SQL Management Studio 中执行相同的查询会导致错误:
消息 232,第 16 级,状态 3,第 3 行 int 类型的算术溢出错误,值 = -1000000000000000000000000000000.000000。
很明显,该函数应该返回 false,因为值超出了 int 数据范围,但错误处理未检测到错误。为什么?从其他帖子我的理解是SqlDataReader reader = cmd.ExecuteReader() 应该会导致错误。
private bool GetIfExists(string SQL, out int ErrorNumber, out bool Exists)
{
bool IsSuccess = true;
ErrorNumber = 0;
Exists = false;
try
{
using (SqlConnection cnn = new SqlConnection(_connectionString))
{
try
{
cnn.Open();
using (SqlCommand cmd = cnn.CreateCommand())
{
cmd.CommandText = SQL;
cmd.CommandTimeout = _commandTimeout;
try
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
Exists = reader.HasRows;
}
}
catch (SqlException ex)
{
if (ex.Errors.Count > 0) ErrorNumber = ex.Errors[0].Number;
throw;
}
catch
{
throw;
}
}
}
catch
{
throw;
}
finally
{
cnn.Close();
}
}
}
catch
{
IsSuccess = false;
}
return IsSuccess;
}
【问题讨论】:
-
为什么这么多接球?此外,using 语句的重点是您不必自己调用诸如 SqlConnection.Close() 之类的东西,您正在明确地这样做
-
@mjwillis sql语句在问题中
-
@CamiloTerevinto 连接池问题的纯粹恐惧。它可能过度了。
-
附带说明,您不需要
cnn.Close();-using会为您处理这些问题。 -
@Peter,我认为在
Exists = reader.HasRows;之后添加reader.NextResult();会引发错误(dbdelta.com/the-curious-case-of-undetected-sql-exceptions)。告诉我,我会详细回答。
标签: c# .net sql-server sqldatareader