【问题标题】:C# SQL connection String in class connection issue类连接问题中的 C# SQL 连接字符串
【发布时间】:2017-01-23 15:29:53
【问题描述】:

所以我注意到我的代码中有很多重复的连接字符串,因此决定稍微清理一下。

我的问题是,现在我已将连接字符串放入单独的类中,使用 using (InfoTableConnection = new SqlConnection(infoTableConnString)) 时无法再打开连接

但是,如果我不使用using,它可以正常工作。

我猜我不太明白它是如何工作的。这是我的代码,如果有人可以解释将其引入类和/或如何修复它后到底发生了什么。

连接类:Connection.cs

class Connection
    {
        public static SqlConnection InfoTableConnection = null;
        public void InfoConnection()
        {
            string infoTableConnString = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=MTRInfoTables;Integrated Security=True";

            using (InfoTableConnection = new SqlConnection(infoTableConnString))

            InfoTableConnection.Open();

        }
    }

示例代码来自: MainForm.cs

private void zGradeCombo()
        {
            try
            {

                //Connection string from class.
                Connection connInfoTable = new Connection();
                connInfoTable.InfoConnection();

                SqlCommand cmd = new SqlCommand();
                cmd.Connection = Connection.InfoTableConnection;
                cmd.CommandText = "SELECT * FROM [dbo].[Item] ORDER by [Type] ASC";

                SqlDataReader reader = cmd.ExecuteReader();

                while (reader.Read())
                {
                    cmbType.Items.Add(reader["Type"].ToString());
                }

                //Close connection from "Connection" class
                Connection.InfoTableConnection.Close();
            }

            //Catch Exception
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "SQL ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

【问题讨论】:

  • using 关键字会在相关对象离开 using 块后将其处理掉,因此您的连接仅在调用 InfoTableConnection.Open(); 之前存在,然后将其处理掉
  • 那么既然它在打开后就释放了连接,就没有办法在一个类中使用它并从一个单独的表单中调用它?
  • 如果您不使用using 也可以,但完成后您必须致电InfoTableConnection.Dispose()

标签: c# sql class connection


【解决方案1】:

using 关键字可确保您的对象在到达范围末尾时被释放,以便之后清理所有资源

using (InfoTableConnection = new SqlConnection(infoTableConnString))
{
        InfoTableConnection.Open();
} // <- At this point InfoTableConnection will be disposed (and closed) 

由于您关心在您周围的代码中进行处理,因此不需要类的构造函数中的 using 块。但最好在 Connection 类上实现 IDisposable 并像这样使用它:

using(var con = new Connection())
{
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = con.InfoTableConnection;
    cmd.CommandText = "SELECT * FROM [dbo].[Item] ORDER by [Type] ASC";

    SqlDataReader reader = cmd.ExecuteReader();

    while (reader.Read())
    {
        cmbType.Items.Add(reader["Type"].ToString());
    }
}

在您的连接的Dispose() 方法中,您应该处置SQL 连接。

【讨论】:

    【解决方案2】:

    如果您的目标是让您的连接字符串位于一个位置,为什么不将您的连接字符串放在您的 app.config(设置)文件中并从那里的代码中引用它?

    app.config

    <connectionStrings>
        <add name="MyConnectionString" connectionString="Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=MTRInfoTables;Integrated Security=True" />
    </connectionStrings>
    

    code.cs

    string myConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
    

    您必须在引用中包含对System.Configuration.dll 的引用才能使用ConfigurationManager

    这样,您可以继续按照设计使用的方式使用 using 语句。

    【讨论】:

    • 谢谢...这也让它更干净了:)
    猜你喜欢
    • 1970-01-01
    • 2011-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-23
    • 1970-01-01
    相关资源
    最近更新 更多