私は自分のコードで気づいたので、私は繰り返したくさんの接続文字列を持っていて、それを少しきれいにすることに決めました。C#SQL接続クラスのクラス接続の問題
私の問題は、私はusing
を使用していない場合は、今、私はusing (InfoTableConnection = new SqlConnection(infoTableConnString))
を使用しているとき、私は、もはや接続を開くことができる別々のクラスに接続文字列を入れていることしかし、それは正常に動作しています。
私はそれが私が推測する方法を理解していません。いったんクラスに導入されたら、どういうことが起こっているのか、どうやって解決するのか、誰かが説明できるなら、私のコードはここにあります。
Connectionクラス: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(); 'が呼び出されてから –
が処分されるまで接続が存在します。それが開いた後の接続は、クラスでそれを使用し、別のフォームから呼び出す方法はありませんか? – Mokey
'を使用していない場合でも、' InfoTableConnection.Dispose() 'を呼び出す必要があります。 –