본문 바로가기

ASP.NET

[ADO.NET] DB연동-비연결기반 SELECT


이번에는 비연결기반 데이터 베이스 연동에 대해서 알아보겠습니다.
연결기반과는 달리 비연결기반의 데이터베이스 연동에서는
DB에 연결하기 위한 Connection 개체와 SQL문을 실행하기 위한 Command 개체 , 참조한 데이터를 담아두기 위한 DataSet 개체,
DataSet에 데이터를 담고 DataSet에서 수정된 내용을 DB에 적용시키는 DataAdapter 개체가 사용됩니다.

지난번과 마찬가지로 SELECT 프로세스 부터 알아볼까요?

SELECT

<%@ Page Language="C#"Debug="true" %>
// SqlConnection, SqlCommand, SqlDataAdapter 클래스를 사용하기 위해 System.Data.SqlClient
    네임스페이스를 선언합니다.
<%@ Import Namespace="System.Data.SqlClient" %>
//DataSet 클래스를 사용하기 위해 System.Data 네임스페이스를 선언합니다.
<%@ Import Namespace="System.Data" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {  
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TestConnectionString"].ConnectionString);
            SqlCommand cmd = new SqlCommand("SELECT * From Member", con);

            // DataAdapter 개체(ad)를 생성하고 cmd에 대입
            SqlDataAdapter ad = new SqlDataAdapter();
            ad.SelectCommand = cmd;
           
            // DataSet 개체(ds)를 생성하고  Fill()메서드를 통해 해당 DataSet 개체에 데이터베이스로부터 가져온 데이더를 
               채웁니다.
            DataSet ds = new DataSet();
            ad.Fill(ds);

            // DataSet 개체를 DataBind() 메서드를 통해 GridView 컨트롤에 바인딩합니다.
            GridView1.DataSource = ds;
            GridView1.DataBind();
        }
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>제목 없음</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h3>비연결기반 SELECT 예제</h3>
       
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
    </div>
    </form>
</body>

결과!!
DB의 내용이 SELECT되었네요!!