以下代码是否正确关闭了连接..
public static bool Hello(string sqlQuery)
{
SqlDataReader dataReader = null;
var isExist = false;
using (var aeConnection = new SqlConnection(ConnectionString))
{
try
{
var aeCommand = new SqlCommand(sqlQuery, aeConnection)
{
CommandType = CommandType.Text
};
aeConnection.Open();
dataReader = aeCommand.ExecuteReader(CommandBehavior.Default);
while (dataReader.Read())
{
int vinCount;
int.TryParse(dataReader["VINCount"].ToString(), out vinCount);
if (vinCount == 0)
{
isExist = true;
}
}
}
catch (Exception ex)
{
if (dataReader != null)
{
dataReader.Close();
}
}
}
return isExist;
}
答案 0 :(得分:1)
是正确关闭连接。当退出使用块时(通过成功完成或错误),它将被关闭。
using语句被编译成try / finally块
using (var aeConnection = new SqlConnection(ConnectionString))
{
}
它将被视为
SqlConnection aeConnection = null;
try
{
aeConnection = new SqlConnection(ConnectionString);
}
finally
{
if(aeConnection!= null)
((IDisposable)aeConnection).Dispose();
}