public void Sample() { string strConn = "Data Source=.;Initial Catalog=pubs;Integrated Security=SSPI;"; StringBuilder sb = new StringBuilder(); using (SqlConnection conn = new SqlConnection(strConn)) { conn.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandText = "SELECT * FROM Product"; // SqlDataReader 객체를 리턴 SqlDataReader rdr = cmd.ExecuteReader(); // 다음 레코드 계속 가져와서 루핑 while (rdr.Read()) { // C# 인덱서를 사용하여 // 필드 데이타 엑세스 string s = rdr["Name"] as string; sb.Append(s); } // 사용후 닫음 rdr.Close(); } //... sb 데이타 사용 }
// SqlDataReader 객체를 리턴 public SqlDataReader GetDataReader() { SqlConnection conn = new SqlConnection(strConn); conn.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandText = "SELECT * FROM Production.Product"; SqlDataReader rdr = cmd.ExecuteReader(); return rdr; } // SqlDataReader를 사용후 Close private void button1_Click(object sender, EventArgs e) { MySample sample = new MySample(); SqlDataReader dr = sample.GetDataReader(); dr.Read(); data = dr[0].ToString(); dr.Close(); } // 문제점 해결 방법: // System.Data.CommandBehavior.CloseConnection SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);