==> [FrmCategoryModify.aspx] 소스 및 디자인



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FrmCategoryModify.aspx.cs" Inherits="Category_FrmCategoryModify" %>

 

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

 

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

<head runat="server">

    <title></title>

</head>

<body>

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

    <div>

   

        카테고리 수정/삭제<br />

        <br />

        카테고리번호 :

        <asp:TextBox ID="txtCategoryID" runat="server"></asp:TextBox>

        <br />

        카테고리명 :

        <asp:TextBox ID="txtCategoryName" runat="server"></asp:TextBox>

        <br />

        <asp:Button ID="btnModify" runat="server" Text="수정" onclick="btnModify_Click" />

        <asp:Button ID="btnDelete" runat="server" Text="삭제" onclick="btnDelete_Click"

            style="height: 21px" /><br />

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

   

    </div>

    </form>

</body>

</html>

 









-------------------------------------------------------------------------------------




==> [FrmCategoryModify.aspx.cs]





using System;

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

 

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

{

    protected void Page_Load(object sender, EventArgs e)

    {

 

    }

    protected void btnModify_Click(object sender, EventArgs e)

    {

        //[0] 변수 선언부

        string updateQuery = @"

            Update Categories

            Set CategoryName = @CategoryName

            Where CategoryID = @CategoryID";

 

        //[1] 커넥션

        SqlConnection con = new SqlConnection(

            ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

        con.Open();

 

        //[2] 커맨드

        SqlCommand cmd = new SqlCommand(updateQuery, con);

        cmd.CommandType = CommandType.Text;

 

        //[3] 파라미터 추가

        cmd.Parameters.AddWithValue("@CategoryID", txtCategoryID.Text);

        cmd.Parameters.AddWithValue("@CategoryName", txtCategoryName.Text);

 

        //[4] 실행 : Create, Alter, Drop, Insert, Update,Delete는 모두 ExecuteNonQuery()

        int recordAffected = cmd.ExecuteNonQuery();

 

        //[5] 마무리

        lblDisplay.Text = recordAffected.ToString() + "개가 변경됨";

        con.Close();

    }

    protected void btnDelete_Click(object sender, EventArgs e)

    {

        //[0] 변수 선언부

        string deleteQuery = "Delete Categories Where CategoryID = @CategoryID";

 

        //[1] 커넥션

        SqlConnection con = new SqlConnection(

            ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

        con.Open();

 

        //[2] 커맨드

        SqlCommand cmd = new SqlCommand(deleteQuery, con);

        cmd.CommandType = CommandType.Text;

 

        //[3] 파라미터 추가

        cmd.Parameters.AddWithValue("@CategoryID", txtCategoryID.Text);

 

        //[4] 실행 : Create, Alter, Drop, Insert, Update,Delete는 모두 ExecuteNonQuery()

        int recordAffected = cmd.ExecuteNonQuery();

 

        //[5] 마무리

        lblDisplay.Text = recordAffected.ToString() + "개가 변경됨";

        con.Close();

 

    }

}

 

 

 



-------------------------------------------------------------------------------------




[실행결과]

- 수정-

--> 수정하기 전 [SQL Server] - [Market]데이터베이스 - [dbo.Categories]테이블의 화면




--> 웹페이지에서 텍스트박스에 각각 "19/컴퓨터"를 입력하고 수정버튼을 누르면 버튼아래 "레이블"에 빨간색 글씨로 "1개가 변경됨"이라는 텍스트가 출력되면서 [dbo.Categories]테이블이 수정된다.



--> 수정 후 [dbo.Categories]테이블의 화면(위의 그림에서는 [dbo.Categories]테이블의 'CategoryID = 19'인 값은 '노트북'임.)






- 삭제 -

--> 삭제하기 전 [SQL Server] - [Market]데이터베이스 - [dbo.Categories]테이블의 화면



--> 웹페이지에서  "카테고리번호"의 텍스트박스에 '26'을 입력하고 삭제버튼을 누르면 버튼아래 "레이블"에 빨간색 글씨로 "1개가 변경됨"이라는 텍스트가 출력되면서 [dbo.Categories]테이블이 수정된다.



--> 삭제 후 [dbo.Categories]테이블의 화면(위의 그림에서는 [dbo.Categories]테이블의 'CategoryID = 26'의 데이터가 존재했었으나, '삭제' 후 'CategoryID = 26'의 데이터가 [dbo.Categories]테이블에서 삭제된 것을 볼 수 있다.)



Posted by holland14
:
- 비동기실행 테스트는 윈폼이나 콘솔에서만 실행가능하다.

- 동기식(Synchronous) : 하나만 처리

- 비동기식(Asynchronous) : 다중 처리(멀티스레드), AJAX

- 비동기식(Begin ~ End문이 들어가 있음.)

------------------------------------------------------------------------------------------------------




- 콘솔 응용 프로그램 [프로젝트]에서 실행










 ==> [Program.cs]




using System.Data.SqlClient;

using System;

 

class Class1

{

    static void Main()

    {

        // This is a simple example that demonstrates the usage of the

        // BeginExecuteNonQuery functionality.

        // The WAITFOR statement simply adds enough time to prove the

        // asynchronous nature of the command.

     

        string commandText =

            "UPDATE Products SET ProductCount = ProductCount + 1 " +

            "WAITFOR DELAY '0:0:5';" +

            "UPDATE Products SET ProductCount = ProductCount - 1 ";

 

        RunCommandAsynchronously(commandText, GetConnectionString());

 

        Console.WriteLine("Press ENTER to continue.");

        Console.ReadLine();

    }

 

    private static void RunCommandAsynchronously(

        string commandText, string connectionString)

    {

        // Given command text and connection string, asynchronously execute

        // the specified command against the connection. For this example,

        // the code displays an indicator as it is working, verifying the

        // asynchronous behavior.

        using (SqlConnection connection =

                   new SqlConnection(connectionString))

        {

            try

            {

                int count = 0;

                SqlCommand command = new SqlCommand(commandText, connection);

                connection.Open();

 

                IAsyncResult result = command.BeginExecuteNonQuery();

                while (!result.IsCompleted) // 요청이 끝나기 전까지 무엇인가를 처리?

                {

                    Console.WriteLine("Waiting ({0})", count++);

                    // Wait for 1/10 second, so the counter

                    // does not consume all available resources

                    // on the main thread.

                    System.Threading.Thread.Sleep(100);

                }

                Console.WriteLine("Command complete. Affected {0} rows.",

                    command.EndExecuteNonQuery(result));

            }

            catch (SqlException ex)

            {

                Console.WriteLine("Error ({0}): {1}", ex.Number, ex.Message);

            }

            catch (InvalidOperationException ex)

            {

                Console.WriteLine("Error: {0}", ex.Message);

            }

            catch (Exception ex)

            {

                // You might want to pass these errors

                // back out to the caller.

                Console.WriteLine("Error: {0}", ex.Message);

            }

        }

    }

 

    private static string GetConnectionString()

    {

        // To avoid storing the connection string in your code,           

        // you can retrieve it from a configuration file.

 

        // If you have not included "Asynchronous Processing=true" in the

        // connection string, the command is not able

        // to execute asynchronously.

        return "server=.;database=Market;uid=Market;pwd=6750440;asynchronous Processing=true;";

    }

}






------------------------------------------------------------------------------------------------------





[실행결과]






Posted by holland14
:

==> [FrmCategoryView.aspx] 소스 및 디자인 



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FrmCategoryView.aspx.cs" Inherits="Category_FrmCategoryView" %>

 

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

 

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

<head runat="server">

    <title></title>

</head>

<body>

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

    <div>

        <asp:TextBox ID="txtCategoryID" runat="server"></asp:TextBox>

        <asp:Button ID="btnView" runat="server" Text="상세보기" onclick="btnView_Click" />       

        <br />

        번호 :

        <asp:Label ID="lblCategoryID" runat="server"></asp:Label>

        <br />

        카테고리명 :

        <asp:Label ID="lblCategoryName" runat="server"></asp:Label>

        <br />

        부모카테고리:

        <asp:Label ID="lblSuperCategory" runat="server"></asp:Label>

        <br />

        정렬순서 :

        <asp:Label ID="lblAlign" runat="server"></asp:Label>

    </div>

    </form>

</body>

</html>

 









-------------------------------------------------------------------------------------




==> [FrmCategoryView.aspx.cs]




using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data.SqlClient;

using System.Configuration;

using System.Data;

 

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

{

    protected void Page_Load(object sender, EventArgs e)

    {

 

    }

    protected void btnView_Click(object sender, EventArgs e)

    {

        //[1] 커넥션

        SqlConnection con = new SqlConnection(

            ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

        con.Open();

 

        //[2] 커맨드 : 단일 레코드

        SqlCommand cmd = new SqlCommand(

            "Select * From Categories Where CategoryID = @CategoryID", con);

        cmd.CommandType = CommandType.Text;

 

        //[!] 파라미터 추가

        cmd.Parameters.Add("@CategoryID", txtCategoryID.Text);

 

        //[3] 데이터리더

        SqlDataReader dr = cmd.ExecuteReader();

 

        //[4] Read : 문자열/정수형인덱서 또는 GetXxx() 메서드로 읽어오기

        while (dr.Read()) // Read() : 데이터가 읽혀지면 True값 반환

        {

            this.lblCategoryID.Text = dr["CategoryID"].ToString(); // 문자열 인덱서

            this.lblCategoryName.Text = dr[1].ToString(); // 정수(서수)형 인덱서

            if (dr["SuperCategory"] != null) // 널값 처리

            {

                this.lblSuperCategory.Text = dr["SuperCategory"].ToString();

            }

            this.lblAlign.Text = dr["Align"].ToString();

        }

        dr.Close();

        con.Close();

    }

}

 




-------------------------------------------------------------------------------------




[실행결과]

--> 아래그림에서 '텍스트박스'에 [dbo.Categories]테이블에 존재하는 범위의 "CategoryID"값을 대입한 후 "상세보기"버튼을 누르면 해당"CategoryID"값의 데이터가 각각의 레이블에 출력된다.




Posted by holland14
:

==>[FrmCategoryList.aspx] 소스 및 디자인




<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FrmCategoryList.aspx.cs" Inherits="FrmCategoryList" %>

 

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

 

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

<head runat="server">

    <title></title>

</head>

<body>

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

    <div>

        총 레코드 : <asp:Label ID="lblCount" runat="server"></asp:Label>

        <asp:GridView ID="ctlCategoryList" runat="server">

        </asp:GridView>

   

    </div>

    </form>

</body>

</html>

 









-------------------------------------------------------------------------------------




==>[FrmCategoryList.aspx.cs]




using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

 

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

{

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!Page.IsPostBack) // 폼을 처음로드할 때 한번만 읽어와라!

        {

            DisplayData();

            DisplayCount();

        }

    }

 

    private void DisplayCount()

    {

        //[1] 커넥션

        SqlConnection con = new SqlConnection(

            ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

        con.Open();

 

        //[2] 커맨드 : 단일 스칼라 값

        SqlCommand cmd = new SqlCommand("Select Count(*) From Categories", con);

        cmd.CommandType = CommandType.Text;

 

        //[3] 실행

        lblCount.Text = cmd.ExecuteScalar().ToString();

 

        //[4] 마무리        

        con.Close();

    }

 

    private void DisplayData()

    {

        //[1] 커넥션

        SqlConnection con = new SqlConnection(

            ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

        con.Open();

 

        //[2] 커맨드 : 다중 레코드

        SqlCommand cmd = new SqlCommand("Select * From Categories", con);

        cmd.CommandType = CommandType.Text;

 

        //[3] 데이터리더

        SqlDataReader dr = cmd.ExecuteReader();

 

        //[4] 바인딩 : 출력

        ctlCategoryList.DataSource = dr;

        ctlCategoryList.DataBind();

 

        //[5] 마무리

        dr.Close();

        con.Close();

    }

}

 

 

 


-------------------------------------------------------------------------------------




[실행결과]

--> 아래그림의 웹페이지에서 "GridView"에는 [SQL Server] - [Market]데이터베이스 - [dbo.Categories]테이블의 데이터가 출력되었으며, 'GridView'위의 레이블에는 [dbo.Categories]테이블의 "총 레코드"값이 스칼라값(단일값, 22)으로 출력되었다.




Posted by holland14
:

==>[FrmCategoryAdd.aspx] 소스 및 디자인



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FrmCategoryAdd.aspx.cs" Inherits="FrmCategoryAdd" %>

 

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

 

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

<head runat="server">

    <title></title>

</head>

<body>

 

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

    <div>

   

        카테고리 입력 :

        <asp:TextBox ID="txtCategoryName" runat="server"></asp:TextBox>

        <asp:Button ID="btnAdd" runat="server" Text="입력" onclick="btnAdd_Click" />

        <asp:Label ID="lblError" runat="server" ForeColor="Red"></asp:Label>

    </div>

    </form>

</body>

</html>

 









-------------------------------------------------------------------------------------




==>[FrmCategoryAdd.aspx.cs]




using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data; //

using System.Data.SqlClient; //

using System.Configuration; //

 

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

{

    protected void Page_Load(object sender, EventArgs e)

    {

 

    }

    protected void btnAdd_Click(object sender, EventArgs e)

    {

        //[0] 변수 선언부

        string insertQuery =

            //[1] "Insert Into Categories(CategoryName) Values('컴퓨터')";

            //[2] 매개변수 처리 : 컴퓨터 -> " + 변수 + "로 대체 ==> 이런방법은 쓰지 말 것!(SQL인젝션공격에 매우 취약함!)

            //"Insert Into Categories(CategoryName) Values('" + txtCategoryName.Text + "')";

            //[3] Named 매개변수 처리 : @변수

            "Insert Into Categories(CategoryName) Values(@CategoryName)";

 

        //[1] 커넥션

        SqlConnection con = new SqlConnection(

            ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

       

        //[2] 커멘드

        SqlCommand cmd = new SqlCommand(insertQuery, con);

        cmd.CommandType = CommandType.Text;

 

        //[3] 파라미터 추가

        cmd.Parameters.AddWithValue("@CategoryName", txtCategoryName.Text);

       

        //[4] 실행

        try

        {

            con.Open();

            cmd.ExecuteNonQuery();

        }

        catch (SqlException se)

        {

            lblError.Text = se.Message; // 에러메시지 출력

        }

        finally

        {

            if (con.State == ConnectionState.Open)

            {

                con.Close(); // 연결상태라면, 닫기

            }

        }

    }

}

 

 



-------------------------------------------------------------------------------------




[실행결과]

--> 웹페이지에서 '텍스트박스'에 "컴퓨터"를 입력하고 "입력"버튼 클릭.



--> [SQL Server] - [Market] - [dbo.Categories]테이블을 실행해보면 테이블 맨아래 "CategoryID"가 26인 값에 "컴퓨터"가 입력(추가)된 것을 볼 수 있다.



'.NET프로그래밍 > ADO.NET' 카테고리의 다른 글

15. 상세보기  (0) 2009.09.28
14. 출력(CategoryList)  (0) 2009.09.28
12. DbProviderFactory 클래스  (0) 2009.09.25
11. 파라미터(Parameters) 사용  (0) 2009.09.25
10. SqlCommand..::.ExecuteScalar 메서드  (0) 2009.09.25
Posted by holland14
:

==> [FrmDbProviderFactory.aspx]  소스 및 디자인



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FrmDbProviderFactory.aspx.cs" Inherits="FrmDbProviderFactory" %>

 

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

 

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

<head runat="server">

    <title></title>

</head>

<body>

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

    <div>

   

        <asp:GridView ID="ctlCategoryList" runat="server">

        </asp:GridView>

   

    </div>

    </form>

</body>

</html>

 










=====================================================================================




==> [FrmDbProviderFactory.aspx.cs]



using System;

using System.Data;

using System.Data.SqlClient;

using System.Data.Common;

using System.Configuration;

 

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

{

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!Page.IsPostBack)

        {

            DisplayDate();

        }

    }

 

    private void DisplayDate()

    {

        //[!] SQL Server, Oracle, Access DB에서 모두 똑같은 코드로 작성하고자 한다면???

        //[1] Configuration 정보 가져오기

        DbProviderFactory factory = DbProviderFactories.GetFactory(

            ConfigurationManager.ConnectionStrings["ConnectionString"].ProviderName);

 

 

        //[2] 커넥션 : SqlConnection, OleDbConnection 등을 DbConnection으로 통일

        DbConnection con = factory.CreateConnection();

        con.ConnectionString =

            ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

        con.Open();

 

 

        //[3] 커맨드 : SqlCommand, OracleCommand 등을 DbCommand로 공통처리

        DbCommand cmd = factory.CreateCommand();

        cmd.Connection = con;

        cmd.CommandText = "Select * From Categories Where CategoryID Between @First And @Second";

        cmd.CommandType = System.Data.CommandType.Text;

        //[!] 파라미터 추가

        DbParameter first = cmd.CreateParameter();

        first.ParameterName = "@First";

        first.DbType = System.Data.DbType.Int32;

        first.Value = 1;

 

        DbParameter second = cmd.CreateParameter();

        second.ParameterName = "@Second";

        second.DbType = System.Data.DbType.Int32;

        second.Value = 20;

 

        cmd.Parameters.Add(first);

        cmd.Parameters.Add(second);

 

 

        //[4] 데이터리더 : SqlDataReader, OleDbDataReader => DbDataReader

        DbDataReader dr = cmd.ExecuteReader();

 

 

        //[5] 바인딩

        this.ctlCategoryList.DataSource = dr;

        this.ctlCategoryList.DataBind();

 

 

        //[6] 마무리

        con.Close();

    }

}

 

 

 

 

// DbProviderFactory 클래스 - 데이터 소스 클래스의 공급자 구현에 대한 인스턴스를 만드는 데 사용되는 메서드의 집합을 나타냅니다.

 

 



=====================================================================================




[실행결과]













Posted by holland14
:

==> [FrmParameters.aspx]  소스 및 디자인



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FrmParameters.aspx.cs" Inherits="FrmParameters" %>

 

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

 

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

<head runat="server">

    <title></title>

</head>

<body>

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

    <div>

   

        <asp:TextBox ID="txtFirst" runat="server"></asp:TextBox>

        ~<asp:TextBox ID="txtSecond" runat="server"></asp:TextBox>

        번 사이의 카테고리 출력<asp:Button ID="btnSelect" runat="server" Text="가져오기"

            Font-Bold="true" ForeColor="Red" Font-Underline="True"

            BackColor="Yellow" BorderColor="Blue" onclick="btnSelect_Click" />

        <br />

        <asp:GridView ID="ctlCategoryList" runat="server">

        </asp:GridView>

   

    </div>

    </form>

</body>

</html>

 










=====================================================================================




==> [FrmParameters.aspx.cs]



using System;

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

 

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

{

    protected void Page_Load(object sender, EventArgs e)

    {

 

    }

    protected void btnSelect_Click(object sender, EventArgs e)

    {

        //[1] 변수 선언부

        string first = txtFirst.Text;

        string second = txtSecond.Text;

 

        //[2] 커넥션

        using (SqlConnection con = new SqlConnection(

            ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))

        {

            con.Open();

 

            //[3] 커맨드

            SqlCommand cmd = new SqlCommand();

            cmd.Connection = con;

            cmd.CommandText =

                //"Select * From Categories Where CategoryID Between 1 And 20"; //[1] 직접입력

                //"Select * From Categories Where CategoryID Between " + first //[2]

                //    + " And " + second + "";

                //String.Format(@"

                //    Select * From Categories

                //    Where CategoryID Between {0} And {1}", first, second); //[3]번째 코딩방법  / 웹페이지에서 두번째 입력될 자리(FrmParameters.aspx.cs에서 정수형으로 형식 지정을 안해주었기 때문에(여기서는 "Text"형식으로 문자열을 입력받고 있다.)) 15;Drop Table Message;-- 로 입력해서 SQL Server Market데이터베이스의 "Message"테이블을 삭제시킬수도 있다.(-> SLQ인젝션공격)

                "Select * From Categories Where CategoryID Between @First And @Second"; //[4] 가장추천하는 코딩방법

       

            //[!] 파라미터 추가

            cmd.Parameters.AddWithValue("@First", first); // .NET2.0이상부터 사용하는 코드

            //cmd.Parameters.AddWithValue("@Second", second);

            cmd.Parameters.Add("@Second", System.Data.SqlDbType.Int); // .NET1.X에서 사용하는 코드

            cmd.Parameters["@Second"].Value = second;

 

            //[4] 데이터리더

            SqlDataReader dr = cmd.ExecuteReader();

 

            //[5] 바인딩

            ctlCategoryList.DataSource = dr;

            ctlCategoryList.DataBind();

 

            //[6] 마무리

            dr.Close();

        }

    }

}

 

 

 

 

// SqlCommand.Parameters 속성 - SqlParameterCollection을 가져옵니다.

 

// 속성 값

// Transact-SQL 문이나 지정 프로시저의 매개 변수입니다. 기본값은 빈 컬렉션입니다.

 

 



=====================================================================================




[실행결과]

--> [FrmParameters.aspx.cs]에서 파라미터(->SQL 쿼리문의 "변수"에 해당함.)를 사용(추가)하여 코드를 작성한 후, 아래그림의 웹페이지에서 "2개의 텍스트박스"에 [SQL Server]-[Market]데이터베이스-[dbo.Categories]테이블에 존재하는 알맞은 범위의 값을 입력한다.(여기서는 10과 15를 각각 대입하였다.) 




--> 위의 그림에서 '텍스트박스'에 '10'과 '15'를 각각 대입한 후 "가져오기"버튼을 클릭하면, 아래그림과 같이 [SQL Server]-[Market]데이터베이스-[dbo.Categories]테이블의 "CategoryID"가 10번에서 15번 사이의 데이터가 웹페이지의 "GridView"에 출력되는 것을 볼 수 있다.





Posted by holland14
:


==> [FrmExecuteScalar.aspx]  소스 및 디자인

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FrmExecuteScalar.aspx.cs" Inherits="FrmExecuteScalar" %>

 

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

 

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

<head runat="server">

    <title></title>

</head>

<body>

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

    <div>

       

        현재 카테고리 개수 :

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

        <br />

        <br />

        등록된 상품 개수 :

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

   

    </div>

    </form>

</body>

</html>

 



 

 



=====================================================================================

 


==> [FrmExecuteScalar.aspx.cs]




using System;

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

 

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

{

    protected void Page_Load(object sender, EventArgs e)

    {

        DisplayCategoryCount();

        DisplayProductCount();

 

    }

 

    private void DisplayProductCount()

    {

        SqlConnection con = new SqlConnection(

            ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

        con.Open();

 

        SqlCommand cmd = new SqlCommand("Select Count(*) From Products", con);

 

        //[!] 스칼라값 실행

        this.lblProductCount.Text = cmd.ExecuteScalar().ToString(); // 실행결과를 문자열로

 

        con.Close();

    }

 

    private void DisplayCategoryCount()

    {

        using (SqlConnection con = new SqlConnection(

            ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))

        {

            con.Open();

 

            SqlCommand cmd = new SqlCommand("Select Count(*) As Cnt From Categories", con);

 

            SqlDataReader dr = cmd.ExecuteReader();

            while (dr.Read())

            {

                lblCategoryCount.Text = dr["Cnt"].ToString(); // 카운트 출력

            }

        } // con.Close();

    }

}

 

 

 

// 단일값 반환(처리) 할 때는 ExecuteScalar()로 처리하면된다.

 

// SqlCommand..::.ExecuteScalar 메서드- 쿼리를 실행하고 쿼리에서 반환된 결과 집합의 첫 번째 행의 첫 번째 열을 반환합니다. 추가 열이나 행은 무시됩니다.

 

 


=====================================================================================




[실행결과]

--> 아래그림은 [FrmExecuteScalar.aspx.cs]에서 "cmd.ExecuteScalar()"메서드를 사용하여 "등록된 상품 개수"라고 쓰여있는 레이블인 "lblProductCount"에 등록된 상품 개수의 "단일값"(=스칼라값 / 집계함수인 "Count()"는 단일값을 반환한다.)을 반환하여 출력하도록 하였으며("결과값:31"), "현재 카테고리 개수"라고 쓰여있는 레이블인 "lblCategoryCount"에는 "cmd.ExecuteReader()"메서드를 사용하여 현재 카테고리 개수의 "단일값"(카운트, 집계함수Count())을 출력해보았다.("결과값:20")










Posted by holland14
:



==> [web.config]  소스 

 

               </sectionGroup>

        </configSections>

        <appSettings/>

 

  <!-- 현재 웹 사이트 전체에서 사용되는 데이터베이스 연결문자열 설정 -->

  <connectionStrings>

    <add

        name="ConnectionString"

        connectionString="server=.;database=Market;uid=Market;pwd=6750440;"

        providerName="System.Data.SqlClient"/>

    <add

        name="GuestBookConnectionString"

        connectionString="server=.;database=GuestBook;uid=GuestBook;pwd=6750440;"

        providerName="System.Data.SqlClient"/>

  </connectionStrings>

     

        <system.web>

               <!--

            컴파일된 페이지에 디버깅 기호를 삽입하려면

            compilation debug="true"로 설정하십시오. 이렇게

            하면 성능에 영향을 주므로 개발하는 동안에만

            이 값을 true로 설정하십시오.

        -->

               <compilation debug="true">

                       <assemblies>




=====================================================================================

 


==> [FrmConfigurationManager.aspx.cs]


 

using System;

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

 

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

{

    protected void Page_Load(object sender, EventArgs e)

    {

        // Web.config 파일에 있는  <connectionStrings> 섹션에 있는 값 읽어오기

        string str =

            ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

               

        Response.Write(str + "<br />"); // 출력

 

        str = ConfigurationManager.ConnectionStrings["ConnectionString"].ProviderName;

        Response.Write(str + "<br />"); // 출력

    }

}

 

 

// ConfigurationManager.ConnectionStrings 속성 - 현재 응용 프로그램의 기본 구성에 대한 ConnectionStringsSection 데이터를 가져옵니다.

// ConnectionStringsSection 개체에는 구성 파일의 connectionStrings 섹션 내용이 포함되어 있습니다.

 

 

 
=====================================================================================

 


[실행결과]


--> 아래그림은 "web.config"파일에 저장되어 있는 "데이터베이스연결문자열(정보)"을 [FrmConfigurationManager.aspx.cs]에서 "Response.Write"문을 사용하여 웹페이지에 출력한 것을 보여준다.
 
 

 

 

 

 

 

'.NET프로그래밍 > ADO.NET' 카테고리의 다른 글

11. 파라미터(Parameters) 사용  (0) 2009.09.25
10. SqlCommand..::.ExecuteScalar 메서드  (0) 2009.09.25
ADO.NET복습  (0) 2009.09.25
8. SqlError 클래스  (0) 2009.09.24
7. SqlDataReader.Read 메서드  (0) 2009.09.24
Posted by holland14
:

==> [FrmADONET.aspx] 소스 및 디자인



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FrmADONET.aspx.cs" Inherits="FrmADONET" %>

 

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

 

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

<head runat="server">

    <title></title>

</head>

<body>

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

    <div>

   

        <asp:TextBox ID="txtCategoryName" runat="server"></asp:TextBox>

        <asp:Button ID="btnAdd" runat="server" Text="카테고리입력" onclick="btnAdd_Click" />

        <br />

        <asp:GridView ID="ctlCategoryList" runat="server">

        </asp:GridView>

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

    </div>

    </form>

</body>

</html>

 











-------------------------------------------------------------------------------------




==> [FrmADONET.aspx.cs]




using System;

using System.Data;

using System.Data.SqlClient;

using System.Configuration; //[0]

 

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

{

    protected void Page_Load(object sender, EventArgs e)

    {

        //[1] 페이지 로드시 모든 카테고리 리스트 출력

        if (!Page.IsPostBack) // !Page.IsPostBack - 페이지가 깜빡거릴때...

        {

            DisplayData();

        }

    }

 

    //출력

    private void DisplayData()

    {

        SqlConnection con = new SqlConnection(

            "Data Source=.;Initial Catalog=Market;User ID=Market;Password=6750440;");

        con.Open();

 

        SqlCommand cmd = new SqlCommand("Select * From Categories", con);

        cmd.CommandType = CommandType.Text;

 

        //[!] ExecuteReader() 메서드의 결과값을 DataReader 개체에 담기

        SqlDataReader dr = cmd.ExecuteReader();

 

        // GridView에 바인딩

        this.ctlCategoryList.DataSource = dr; // DataReader, DataSet, List<T> 등이 담김

        this.ctlCategoryList.DataBind(); // 그러면, 알아서 모양 만들어 출력

 

        dr.Close(); // 데이터리더도 반드시 Close()해야 함...

 

        con.Close();

    }

 

    // 입력/수정/삭제

    protected void btnAdd_Click(object sender, EventArgs e)

    {

        //[0] 변수 선언부

        string strCategoryName = txtCategoryName.Text.Trim();

 

        //[1]커넥션

        SqlConnection objCon = new SqlConnection();

        objCon.ConnectionString = //"server=.;database=Market;uid=Market;pwd=6750440;";

            ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

        objCon.Open();

 

        //[2] 커맨드

        SqlCommand objCmd = new SqlCommand();

        objCmd.Connection = objCon; // 오픈될 커넥션 개체 지정

        objCmd.CommandText = String.Format(

            "Insert Categories(CategoryName) Values('{0}')", strCategoryName); // 명령어

        objCmd.CommandType = CommandType.Text; // 타입지정

 

        //[3] 실행 : ExecuteNonQuery(), ExecuteReader(), ExecuteScalar(), ExecuteDataSet()

        int rows = objCmd.ExecuteNonQuery(); // 모든 명령어 실행 <-> Select도 가능-Reader를 사용

        this.lblDisplay.Text = rows.ToString() + "개 입력되었습니다.";

 

        //[4] 마무리

        objCon.Close();

 

 

    }

}

 

 

 
-------------------------------------------------------------------------------------




[실행결과]


--> 아래그림에서 '텍스트박스'에 "자동차"를 입력하고 "카테고리입력"버튼을 누르면 GridView아래에 있는 레이블에 "1개 입력되었습니다."라는 텍스트가 출력된다.





--> [SQL Server]내의 [Market]데이터베이스 - [dbo.Categories]테이블을 '실행'버튼을 눌러 실행해보면, [dbo.Categories]테이블의 'CategoryID'가 20번째에 위의그림의 웹페이지에서 입력한 자료인 "자동차"가 저장된 것을 볼 수 있다.




--> 아래그림에서 웹페이지를 새로 열어보면 "GridView"에서도 'CategoryID'가 20번째에 "자동차"가 저장되어 있는 것을 볼 수 있다.







Posted by holland14
: