使用的SqlConnection /命令语句+ try / catch块 [英] sqlConnection/Command using statement + try/catch block

查看:441
本文介绍了使用的SqlConnection /命令语句+ try / catch块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是内部使用,或者使用内部的try / catch?



 使用(SqlConnection的连接= CreateSqlConnection一个正确的方法的try / catch (CONNSTRING))
{
使用(的SqlCommand命令= CreateSqlCommand()
{
试{//打开连接+执行命令+去做别的事情}
赶上{ //做一些事情}
}
}

VS

 使用试
{
使用(SqlConnection的连接= CreateSqlConnection(CONNSTRING))
{
(命令的SqlCommand = CreateSqlCommand()
{
//打开连接+执行命令+去做别的事情
}
}
}

{
//做些什么
}


解决方案

这是我的观点:

 
{
使用(SqlConnection的连接= CreateSqlConnection (CONNSTRING))
{
使用(的SqlCommand命令= CreateSqlCommand()
{
//打开连接+执行命令+去做别的事情
}
}
}

{
//做些什么
}

以上是正确的方法。



由于,与是否有异常,并连接到数据库,这将陷入catch块中这种方法..但与第一种方式,它不会。


What is a correct approach try/catch inside using or using inside try/catch?

using (SqlConnection connection = CreateSqlConnection(connString))
{
               using (SqlCommand command = CreateSqlCommand()
               {
                   try{//open connection + execute command + do something else}
                   catch{//do something}
               }
}

vs.

try
{
    using (SqlConnection connection = CreateSqlConnection(connString))
    {
               using (SqlCommand command = CreateSqlCommand()
               {
                   //open connection + execute command + do something else
               }
    }
}
catch
{
 //do something
}

解决方案

From my point of view:

try
{
    using (SqlConnection connection = CreateSqlConnection(connString))
    {
               using (SqlCommand command = CreateSqlCommand()
               {
                   //open connection + execute command + do something else
               }
    }
}
catch
{
 //do something
}

Above is the correct way.

Because , with this approach if there is exception with connection to database, that will get caught inside catch block.. But with first approach, it will not.

这篇关于使用的SqlConnection /命令语句+ try / catch块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆