제목 : 예제. DataReader 클래스를 사용한 Select문 실행
using System; using System.Data; using System.Data.SqlClient;
namespace dotnetkorea.com{
public class Connection클래스{
public static void Main(){
string strCon = "server=localhost;database=dotnet;"
+ "user id=dotnet;password=dotnet";
SqlConnection objCon = new SqlConnection(strCon);
try{
objCon.Open();
SqlCommand objCmd = new SqlCommand();
objCmd.Connection = objCon;
objCmd.CommandText = "Select * From Dotnet";
objCmd.CommandType = CommandType.Text;
SqlDataReader objDr;
objDr = objCmd.ExecuteReader();
for(int i = 0; i<objDr.FieldCount;i++){
Console.WriteLine("필드명 : {0}", objDr.GetName(i));
}
Console.WriteLine("--------------------");
while(objDr.Read()){
Console.WriteLine("{0}\t{1}", objDr[0], objDr["Pwd"]);
}
objDr.Close();
}
catch(Exception e){
Console.WriteLine("아래와 같은 사항으로 예외가 발생하였습니다.");
Console.WriteLine("이유 : " + e.Message);
}
finally{
objCon.Close();
}
}
}
}