关于sqlconnection打开的问题 [英] Question about sqlconnection open

查看:89
本文介绍了关于sqlconnection打开的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例1

Example 1

public class foo() 
{
   public void InsertDatabase() 
   {
      using (SQLConnection conn=new SQLConnection("connection info")) 
      {
         conn.Open()
         conn.CommandText="Insert into database";
         conn.ExecuteNonQuery();
      }
   }
}

public void main()
{
   foo f= new foo();
   foo.InsertDatabase();
}



OR

示例2




OR

Example 2


public class foo():Idisposable
{
   private SQLConnection sql=new SQLConnection();

   public void OpenDB()
   {
     sql.Open(); 
   }

   public void InsertDatabase()
   {
     sql.commandtext="Insert into database";
     sql.executenonquery();
   }

//Idisposable methods would go here

}

public void main()
{
    using (foo f= new foo()) 
    {
       foo.OpenDB();
       foo.InsertDatbase();
    }
}



您可以看到两个示例,一个示例将在InsertDatabase方法中打开,另一个示例将使用open方法,然后使用InsertDatabase方法.我意识到使用连接池打开和关闭并不是一个真正的问题,但是实现此目的的最佳实践方法是什么.



You can see the two examples, one would have open in the InsertDatabase method and the other would have an open method and then the InsertDatabase method. I realize with connection pooling opening and closing isnt really an issue, but what is the best practice way to do this. Most people online tend to lean toward example 1, but is this right?

推荐答案

编写方法时,该方法的名称应明确指出什么是方法1.方法可以,仅此而已.因此,我倾向于您的第二个示例,因为InsertDatabase应该只插入数据库中. OpenDB简短而有趣,但是如果您想对它进行一些通用的验证,则只需在该方法中执行一次即可,因此是双赢的.但是,两者都没有错.如果您还有其他项目来源可以查看您的工作地点,则可以查看这些内容并撰写与之相符的内容.
When you write methods, then name of the method should give a clear indication of what the method does, and nothing more. So I would lean towards your second example because InsertDatabase should only insert into a database. OpenDB is short and sweet, but if you want to wrap some generic validation around it, you will only have to do it once in that method, so it is a win win. Neither is wrong, however. If you have other project source to look at where you work, you could look at those and write yours to be consistent with those.


尝试使用此代码进行Open Connection ...

Try this code for Open Connection...

public void InsertDatabase()
   {
try
{      
using (SQLConnection conn=new SQLConnection("connection info"))
      {
         conn.Open();
         conn.CommandText="Insert into database";
         conn.ExecuteNonQuery();
      }
}
catch(exception ex)
{
messagebox.show(ex.tostring());
}
finally
{
conn.close();
}
   }


没有最佳实践.它更符合样式和项目要求.我喜欢的人就像您的第一个例子.有时是另一种方式.但是我总是在数据库访问内容周围放置try/catch块.
There is no best practice on this. It''s more amatter of style and project requirements. Someones I do it like your first example. Sometimes the other way. But I DO always put a try/catch block around db access stuff.


这篇关于关于sqlconnection打开的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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