【发布时间】: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