C#数据库操作时,优先使用using还是try...catch,为什么?

来源:百度知道 编辑:UC知道 时间:2024/09/20 20:39:01
如题。
对于数据库操作有哪些常见的异常?下面是我程序中的代码,我如何确定它是否会出现异常?
using (SqlConnection connect = new SqlConnection(conStr))
{
connect.Open();
using (SqlCommand command = new SqlCommand("addCardFailed",connect))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@userNumber",SqlDbType.Char);
command.Parameters["@userNumber"].Value=userNumber;
command.Parameters.Add("@productId",SqlDbType.VarChar);
command.Parameters["@productId"].Value = productId;
command.Parameters.Add("@doaction",SqlDbType.TinyInt);
command.Parameters["@doaction"].Value = 0;
command.ExecuteNonQuery();
}
}

如果强调调用dispose使用using
强调异常处理使用try..catch
如果写程序的时候知道错误是什么,就用using+if,不建议使用try catch
using 语句确保调用 Dispose,即使在调用对象上的方法时发生异常也是如此
通过将对象放入 try 块中,并在调用 finally 块中的Dispose,可以获得相同的结果

try...catch 可以理解为C#中的触发器 主要是为了发现和避免不必要的错误

using和try...catch之间没有特定的规定谁先谁后 但是一般的格式 using总是作为类似统称一样的放在程序最前面的

使用using语句实际上生成的IL代码中是一个try, finally代码块,在finally代码块里释放资源。

那要看你的代码才知道啊,
如果你using中有可能会出现异常,就先try一下了,
否则就在using里try...catch呀!

怎么说呢 using方便一点因为你可以不去关闭数据库连接释放资源了 要不你用try catch还要每次都去释放一下挺麻烦的 其实using最后还是在生成一个try catch语句 然后在finally里面执行释放语句