블로그 이미지
Magic_kit
study 관련자료를 한곳으로 자기 개발 목적으로 재태크 재무 관리 목적으로 일상생활의 팁을 공유 하기 위하여 블로그를 개설 하였습니다.

calendar

1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28

Category

Recent Post

Recent Comment

Archive

2009. 9. 24. 14:28 .Net Project/ADO.NET 3.5
반응형

--  sqlError 처리

 


 protected void btnConnect_Click(object sender, EventArgs e)
    {

        //Connection
        SqlConnection con = new SqlConnection();
        con.ConnectionString =
                "server=.;database=Market;uid=Market;pwd=1234;";
             
        //Command
        SqlCommand cmd = new SqlCommand
                                    ("Select *From categories", con);
        cmd.CommandType = CommandType.Text;

        //Data Reader
        try
        {
            con.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            this.lblError.Text = "연결완료";
           
            con.Close();
        }
        catch (SqlException se)
        {

            SqlErrorCollection sec = se.Errors;

            //에러를 묶어서 출력 (예외 처리 의해 에러 발생)
            string msg = "";
            foreach (var item in sec) //[3] 에러 하나를 담는 클래스
            {
                msg += item.ToString() + "<br />"; //.Message : 에러 메시지
            }
            this.lblError.Text = msg;
        }
    }


--sqlConnectionWithUsing

     

                                                  
public partial class FrmSqlConnectionWithUsing : System.Web.UI.Page
{
    private string ConnectionString; //필드 : 데이터베이스 연결문자열
    //생성자(Ctor + 탭 + 탭)
    public FrmSqlConnectionWithUsing()
    {
        ConnectionString = 
                      "server=.;database=Market;uid=Market;pwd=1234;";
    }
    protected void Page_Load(object sender, EventArgs e)
    {
            //Empty
    }
    protected void btnConnection1_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(ConnectionString);
        con.Open();
        this.lblDisplay.Text = "연결완료";
       
        con.Close(); //using구문 사용하면 생략 가능
    }
    protected void btnConnection2_Click(object sender, EventArgs e)
    {
        //using()안에서 생성된 DB는 using 구문이 끝나면 자동으로 닫힌다.
        using (SqlConnection con = new SqlConnection(ConnectionString))
        {
            con.Open();
            this.lblDisplay.Text = "연결완료";           
        } //using 구문의 마지막 } 가 실행되면 ,자동으로 Close되므로 생략 가능
    }
}



반응형
posted by Magic_kit