제목 : 예제. Command 클래스와 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();
Console.WriteLine("Dotnet 테이블의 레코드 출력");
Console.WriteLine(objDr.GetName(0) + "\t" + objDr.GetName(1));
while(objDr.Read()){
Console.WriteLine("{0}\t{1}\t{2}", objDr[0], objDr["Pwd"], objDr.GetString(0));
}
objDr.Close();
}
catch(Exception e){
Console.WriteLine("아래와 같은 사항으로 예외가 발생하였습니다.");
Console.WriteLine("이유 : " + e.Message);
}
finally{
objCon.Close();
}
}
}
}