如何正确处理SQL命令?
我的问题是我的代码总是返回false,因为我的sqlcommand不等于null
我怎样才能解决这个问题?
这是我的代码:
private SqlCommand Command()
{
cmd = new SqlCommand(QueryStr, Connection);
cmd.StatementCompleted += new StatementCompletedEventHandler(cmd_StatementCompleted);
return cmd;
}
private void cmd_StatementCompleted(object sender, StatementCompletedEventArgs e)
{
((SqlCommand)sender).Dispose();
}
public object GetScalarResult()
{
Command();
cmd.CommandType = CommandType;
con.Open();
return cmd.ExecuteScalar();
}
public bool IsDisposedChecker()
{
if (cmd == null)
{
return true;
}
else
{
return false;
}
}
我的IsDisposedChecker函数总是返回false,这意味着sqlcommand没有正确处理?
答案 0 :(得分:1)
Dispose()
不将指针重置为null。所以ISDisposedChecker函数不能这样工作..
Dispose不是析构函数..
我不会实现dispose-checker,如果你想返回SqlCommand,我会把Dispose责任放到调用方法中。
private SqlCommand Command()
{
cmd = new SqlCommand(QueryStr, Connection);
return cmd;
}
private void Test()
{
// a using block is very safe, it will dispose the command
// even when exceptions are thrown.
using(SqlCommand command = Command())
{
// do your thing....
}
}