C#

SqlCommand 재사용(Reuse) 하기

by kay posted Jul 10, 2013
?

단축키

Prev이전 문서

Next다음 문서

ESC닫기

크게 작게 위로 아래로 댓글로 가기 인쇄

SqlCommand 재사용하는 방법입니다..


using 내에서 선언된 변수는

해당 구문이 끝나는 시점에서 Dispose , Close 가 된다고 합니다..

 

참고 Url : http://stackoverflow.com/questions/10146979/reuse-of-sqlconnection-and-sqldatareader


private void frmCityMapping_Load(object sender, EventArgs e) {
  try {
    string ConnectionString = "server=xxx.xxx.xxx.xxx;database=DataBase;uid=userId;pwd=password"; 
    SqlConnection dbConn = new SqlConnection(ConnectionString);
    dbConn.Open();
    SqlCommand cmd = new SqlCommand("SELECT code,name FROM tblsply order by name", dbConn);
    
    using(var myReader = cmd.ExecuteReader()) {
      while (myReader.Read()) {
        code.Items.Add(new comboboxItem(myReader["name"].ToString(), myReader["code"].ToString()));
      }
      code.SelectedIndex = 0;
    }
    
    cmd.CommandText = "SELECT nationCd,nationName FROM tblNation order by nationName";
    using(var myReader = cmd.ExecuteReader()) {
      while (myReader.Read()) {
        nationCd.Items.Add(new comboboxItem(myReader["nationName"].ToString(), myReader["nationCd"].ToString()));
      }
      nationCd.SelectedIndex = 0;
    }
    dbConn.Dispose();
    dbConn.Close();
  } catch (Exception b) {
    MessageBox.Show(b.ToString());
  }
}


public class comboboxItem {
    public string Text {
        get;
        set;
    }
    public object Value {
        get;
        set;
    }

    public override string ToString() {
        return Text;
    }
    public comboboxItem(string text, object value) {
        Text = text;
        Value = value;
    }
}




string ConnectionString = "server=xxx.xxx.xxx.xxx;database=DataBase;uid=userId;pwd=password"; 
SqlConnection dbConn = new SqlConnection(ConnectionString);
dbConn.Open();

SQL = "UPDATE tblcity SET nationCd = 'AAA' WHERE nationCd='BBB'";
using (var cmd = new SqlCommand(SQL, dbConn))
{ 
	cmd.ExecuteNonQuery();
}

SQL = "UPDATE tblnation SET nationCd='AAA' WHERE nationCd='BBB'";
using (var cmd = new SqlCommand(SQL, dbConn))
{
	cmd.ExecuteNonQuery();
} 
dbConn.Close();
dbConn.Dispose();