class 连接问题中的 C# SQL 连接字符串

C# SQL connection String in class connection issue

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

我的问题是,既然我已经将连接字符串放入单独的 class 中,我在使用 using (InfoTableConnection = new SqlConnection(infoTableConnString))

时无法再打开连接

然而,如果我不使用 using 它工作正常。

我猜我不太明白它是如何工作的。这是我的代码,如果有人可以解释一旦它被引入 class and/or 如何修复它到底发生了什么。

连接Class: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 = new SqlConnection(infoTableConnString))
{
        InfoTableConnection.Open();
} // <- At this point InfoTableConnection will be disposed (and closed) 

由于您关心的是在周围的代码中进行配置,因此不需要 class 的构造函数中的 using 块。但是最好在您的 Connection class 上实现 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 连接。

如果您的目标是让您的连接字符串位于一个位置,为什么不将您的连接字符串放在您的 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 语句,它们的设计目的就是为了使用它们。