因此,我在代码中注意到我有很多重复的连接字符串,并决定对其进行一些清理。
我的问题是,现在我已将连接字符串放入一个单独的类中,在使用时无法再打开连接 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);
}
}
如果您的目标是将连接字符串放在一个位置,为什么不将连接字符串放在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
按照设计使用的方式继续使用您的语句。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句