Mad*_* Zu 2 .net c# asp.net stored-procedures
我正在尝试习惯使用C#中的"使用"块,但我很难理解何时应该使用它们.
这是一个例子.
我的原始代码,没有using块:
SqlConnection conn = new SqlConnection(cCon.getConn());
SqlCommand cmd = new SqlCommand("sp_SaveSomething", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@x", xxx));
cmd.Parameters.Add(new SqlParameter("@ORG", ORG));
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{ }
finally
{
conn.Close();
}
Run Code Online (Sandbox Code Playgroud)
但我真的应该这样做吗?或者我应该使用(SqlConnection conn = new SqlConnection(cCon.getConn()))?请帮我理解这个.我最初这样做的方式错了吗?
SqlConnection conn = new SqlConnection(cCon.getConn());
using( SqlCommand cmd = new SqlCommand("sp_SaveSomething", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@x", xxx));
cmd.Parameters.Add(new SqlParameter("@ORG", ORG));
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{ }
finally
{
conn.Close();
}
}
Run Code Online (Sandbox Code Playgroud)
Dar*_*rov 10
但是我很难理解我何时应该使用它们.
这很简单.每次处理实现IDisposable接口的类时,都应该使用它们.像这样:
using (SqlConnection conn = new SqlConnection(cCon.getConn()))
using (SqlCommand cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "sp_SaveSomething";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@x", xxx));
cmd.Parameters.Add(new SqlParameter("@ORG", ORG));
cmd.ExecuteNonQuery();
}
Run Code Online (Sandbox Code Playgroud)
如果你想处理一些异常,你可以在try/catch语句中包装你想要处理的代码:
try
{
using (SqlConnection conn = new SqlConnection(cCon.getConn()))
using (SqlCommand cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "sp_SaveSomething";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@x", xxx));
cmd.Parameters.Add(new SqlParameter("@ORG", ORG));
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
// do something here with the exception, don't just consume it,
// otherwise it's meaningless to catch it
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,所有IDisposable资源(此代码段中的SqlConnection和SqlCommand)现在都已正确包装在using 语句中,这些语句可确保即使抛出异常也能正确处理它们.因此,您不再需要使用finally语句并明确地执行此操作.
还要记住,ADO.NET使用的connection pool含义是,当您.Open()在SqlConnection上调用方法时,您没有打开与数据库的物理连接.你只是在游泳池中画一个.当您调用.Close(或.Dispose)方法时,您没有关闭连接.您只需将其返回到连接池,以便可以重复使用它.
| 归档时间: |
|
| 查看次数: |
2316 次 |
| 最近记录: |