C#SQL连接类连接问题

时间:2017-01-23 15:29:54

标签: c# sql class connection

所以我注意到在我的代码中我有很多重复的连接字符串,并决定将其清理一下。

我的问题是,现在我已将连接字符串放入单独的类中,但在使用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);
            }
        }

2 个答案:

答案 0 :(得分:5)

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连接。

答案 1 :(得分:1)

如果您的目标是将连接字符串放在一个位置,为什么不将连接字符串放在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语句。

相关问题