【问题标题】:The proper way to connect to a database using C#使用 C# 连接到数据库的正确方法
【发布时间】:2014-01-30 11:19:09
【问题描述】:

我目前正在使用连接到我机器上本地 SQL Server 数据库的应用程序。我有许多 SQL 查询当前使用不同的方法执行得很好。我的问题是关于不同方法之间数据库连接的打开/关闭。

我有 2 种方法看起来像这样:

Class MyClass
{
    string connectionString = "myConnectionString";

    public void Method1()
    {
        SqlConnection con = new SqlConnection(connectionString);
        con.Open();
        string sqlStr = "my SQL query";
        SqlCommand com = new SqlCommand(sqlStr, con);
        com.ExecuteNonQuery();
        con.Close();
    }

    public void Method2()
    {
        SqlConnection con = new SqlConnection(connectionString);
        con.Open();
        string sqlStr = "my SQL query";
        SqlCommand com = new SqlCommand(sqlStr, con);
        com.ExecuteNonQuery();
        con.Close();
    }
}

如果我调用这些方法,它们可以正常工作,没有例外。但这是处理数据库连接的正确方法吗?例如,我可以使用在 MyClass 初始化后立即初始化的静态连接吗?像这样

Class MyClass
{
    string connectionString = "myConnectionString";
    SqlConnection con = new SqlConnection(connectionString);
    con.Open();

    public void Method1()
    {
        ...
    }
    etc.

或者有没有“更好”的方式来处理数据库连接?

感谢您的任何意见。

【问题讨论】:

    标签: c# sql-server database-design connection database-connection


    【解决方案1】:

    每当您使用IDisposable 实例时,您宁愿使用

    public void Method3() {
      string sqlStr = "my SQL query";
    
      // Do not forget to configure connection pull so that
      // establishing a connection will not be expensive 
      using (SqlConnection con = new SqlConnection(connectionString)) {
        con.Open();
    
        using (SqlCommand com = new SqlCommand(sqlStr, con)) {
          com.ExecuteNonQuery();
        }
      }
    }
    

    您可以根据需要组合查询:

        public void Method4() {
          string sqlStr1 = "my SQL query 1";
          string sqlStr1 = "my SQL query 2";
    
          // Do not forget to configure connection pull so that
          // establishing a connection will not be expensive 
          using (SqlConnection con = new SqlConnection(connectionString)) {
            con.Open();
    
            // Think on having both queries executed in one transaction
            using (SqlCommand com1 = new SqlCommand(sqlStr1, con)) {
              com1.ExecuteNonQuery();
            }
    
            using (SqlCommand com2 = new SqlCommand(sqlStr2, con)) {
              com2.ExecuteNonQuery();
            } 
          }
        }
    

    静态连接可能很难维护,尤其是。如果你正在实现多线程软件,这就是为什么你应该避免使用它们

    【讨论】:

    • @Dmitry Bychenko 我应该在使用 (....) { .... } 后关闭连接吗?
    • @Marcus:不; using(...) {...} 将为您完成。
    【解决方案2】:

    不要使用静态连接,检查数据库连接字符串以启用连接池。是控制连接的连接池,让它保持打开直到超时(提高性能)并在不需要时关闭它。 对每个一次性对象使用“使用”子句!

    【讨论】:

      猜你喜欢
      • 2011-05-16
      • 2013-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-17
      • 2011-09-11
      • 2011-06-08
      • 1970-01-01
      相关资源
      最近更新 更多