2017-01-23 7 views
0

私は自分のコードで気づいたので、私は繰り返したくさんの接続文字列を持っていて、それを少しきれいにすることに決めました。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); 
      } 
     } 
+1

'using'キーワードは、それがusingブロックを離れた時点で問題のオブジェクトを破棄します。したがって、' InfoTableConnection.Open(); 'が呼び出されてから –

+0

が処分されるまで接続が存在します。それが開いた後の接続は、クラスでそれを使用し、別のフォームから呼び出す方法はありませんか? – Mokey

+0

'を使用していない場合でも、' InfoTableConnection.Dispose() 'を呼び出す必要があります。 –

答えて

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; 

あなたはConfigurationManagerを使用するために、あなたの参考文献にSystem.Configuration.dllへの参照を含める必要があります。

このようにして、使用するように設計されたusingステートメントを引き続き使用することができます。

+0

ありがとうございます。 – Mokey

5

使用したキーワードは、あなたが到達したときに、オブジェクトが配置されることを確認しますすべてのリソースが後で整理されるようにスコープの終わり

using (InfoTableConnection = new SqlConnection(infoTableConnString)) 
{ 
     InfoTableConnection.Open(); 
} // <- At this point InfoTableConnection will be disposed (and closed) 

周囲のコードを処理することに気を使うので、クラスのコンストラクタでusingブロックは必要ありません。あなたはSQL接続を配置する必要があり、あなたの接続のDispose()方法で

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()); 
    } 
} 

:しかし、あなたのConnectionクラスにIDisposableインターを実装し、このようにそれを使用することが良いでしょう。