ASP.NET

08.ADO.NET - 데이터베이스 연결 여러번 사용하기

Godffs 2009. 9. 24. 14:17
반응형
데이터베이스 연결을 여러곳에서 사용하는 예제입니다.

FrmSqlConnectionWithUsing.aspx

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

   

        <asp:Button ID="btnConnection1" runat="server" Text="연결1"

            onclick="btnConnection1_Click" />

        <asp:Button ID="btnConnection2" runat="server" Text="연결2"

            onclick="btnConnection2_Click" />

        <hr />

        <asp:Label ID="lblDisplay" runat="server" Text=""></asp:Label>

   

    </div>

    </form>

</body>

</html>


FrmSqlConnectionWithUsing.aspx.cs

public partial class FrmSqlConnectionWithUsing : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

 

    }

 

    private string connectionString; // 필드 : 데이터베이스연결문자열 저장

   

    public FrmSqlConnectionWithUsing()// 생성자 : 연결문자열 초기화

    {

        connectionString =

            "server=WINDOWS-XP\\SQLSERVER;database=Test;uid=Test;pwd=1234;";

    }

 

    protected void btnConnection1_Click(object sender, EventArgs e) {

        SqlConnection con = new SqlConnection(connectionString);

        con.Open();

        this.lblDisplay.Text = "연결완료"; // 이부분에서 무엇인가를 하고...

        con.Close(); // 반드시 Close 시켜야 한다...

    }

 

    protected void btnConnection2_Click(object sender, EventArgs e) {

        // using()안에서 생성된 DB using 구문이 끝나면 자동으로 닫힌다...

        using (SqlConnection con = new SqlConnection(connectionString))

        {

            con.Open();

            this.lblDisplay.Text = "연결완료";

        } // using 구문의 마지막 } 실행되면, 자동으로 Close되므로 생략가능   

    }

}


결과확인

[그림8-1]



반응형