所以我注意到在我的代码中我有很多重复的连接字符串,并决定将其清理一下.
我的问题是,现在我已将连接字符串放入单独的类中,我在使用时无法再打开连接 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); } }
SirBirne.. 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连接.
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连接.