다음을 통해 공유


SqlDataSource.InsertCommand 속성

정의

컨트롤이 기본 데이터베이스에 SqlDataSource 데이터를 삽입하는 데 사용하는 SQL 문자열을 가져오거나 설정합니다.

public:
 property System::String ^ InsertCommand { System::String ^ get(); void set(System::String ^ value); };
public string InsertCommand { get; set; }
member this.InsertCommand : string with get, set
Public Property InsertCommand As String

속성 값

데이터를 삽입하는 SqlDataSource 데 사용하는 SQL 문자열입니다.

예제

이 섹션에는 두 가지 코드 예제가 포함되어 있습니다. 첫 번째 코드 예제에서는 컨트롤과 간단한 Web Forms 페이지를 사용하여 데이터베이스에 SqlDataSource 데이터를 삽입하는 방법을 보여 줍니다. 두 번째 코드 예제에서는 Microsoft SQL Server에서 데이터를 검색하여 컨트롤에 GridView 표시하는 방법과 컨트롤을 사용하여 DetailsView 컨트롤에 GridView 선택한 행의 세부 정보를 확인하고 폼으로 새 레코드를 삽입하는 방법을 보여 줍니다.

메모

다음 예제에서는 데이터 액세스에 선언적 구문을 사용하는 방법을 보여 줍니다. 태그 대신 코드를 사용하여 데이터에 액세스하는 방법에 대한 자세한 내용은 Visual Studio에서 데이터 액세스를 참조하세요.

다음 코드 예제에서는 컨트롤 및 간단한 Web Forms 페이지를 사용 하 여 데이터베이스에 SqlDataSource 데이터를 삽입 하는 방법을 보여 줍니다. 데이터 테이블의 현재 데이터가 컨트롤에 DropDownList 표시됩니다. 컨트롤에 값을 TextBox 입력한 다음 삽입 단추를 클릭하여 새 레코드를 추가할 수 있습니다. 삽입 단추를 클릭하면 지정된 값이 데이터베이스에 삽입되고 컨트롤이 DropDownList 새로 고쳐집니다.

중요합니다

이 예제에는 잠재적인 보안 위협인 사용자 입력을 허용하는 텍스트 상자가 포함되며, 값은 유효성 검사 없이 매개 변수에 삽입되며 이는 잠재적인 보안 위협이기도 합니다. 쿼리를 Inserting 실행하기 전에 이벤트를 사용하여 매개 변수 값의 유효성을 검사합니다. 자세한 내용은 스크립트 악용 개요를 참조하세요.

<%@Page  Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
private void InsertShipper (object source, EventArgs e) {
  SqlDataSource1.Insert();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" runat="server">

      <asp:dropdownlist
        id="DropDownList1"
        runat="server"
        datasourceid="SqlDataSource1"
        datatextfield="CompanyName"
        datavaluefield="ShipperID" />

<!-- Security Note: The SqlDataSource uses a FormParameter,
     Security Note: which does not perform validation of input from the client.
     Security Note: To validate the value of the FormParameter, handle the Inserting event. -->

      <asp:sqldatasource
        id="SqlDataSource1"
        runat="server"
        connectionstring="<%$ ConnectionStrings:MyNorthwind %>"
        selectcommand="SELECT CompanyName,ShipperID FROM Shippers"
        insertcommand="INSERT INTO Shippers (CompanyName,Phone) VALUES (@CoName,@Phone)">
          <insertparameters>
            <asp:formparameter name="CoName" formfield="CompanyNameBox" />
            <asp:formparameter name="Phone"  formfield="PhoneBox" />
          </insertparameters>
      </asp:sqldatasource>

      <br /><asp:textbox
           id="CompanyNameBox"
           runat="server" />

      <asp:RequiredFieldValidator
        id="RequiredFieldValidator1"
        runat="server"
        ControlToValidate="CompanyNameBox"
        Display="Static"
        ErrorMessage="Please enter a company name." />

      <br /><asp:textbox
           id="PhoneBox"
           runat="server" />

      <asp:RequiredFieldValidator
        id="RequiredFieldValidator2"
        runat="server"
        ControlToValidate="PhoneBox"
        Display="Static"
        ErrorMessage="Please enter a phone number." />

      <br /><asp:button
           id="Button1"
           runat="server"
           text="Insert New Shipper"
           onclick="InsertShipper" />

    </form>
  </body>
</html>
<%@Page  Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
Private Sub InsertShipper (ByVal Source As Object, ByVal e As EventArgs)
  SqlDataSource1.Insert()
End Sub ' InsertShipper
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" runat="server">

      <asp:dropdownlist
        id="DropDownList1"
        runat="server"
        datasourceid="SqlDataSource1"
        datatextfield="CompanyName"
        datavaluefield="ShipperID" />

<!-- Security Note: The SqlDataSource uses a FormParameter,
     Security Note: which does not perform validation of input from the client.
     Security Note: To validate the value of the FormParameter, handle the Inserting event. -->

      <asp:sqldatasource
        id="SqlDataSource1"
        runat="server"
        connectionstring="<%$ ConnectionStrings:MyNorthwind %>"
        selectcommand="SELECT CompanyName,ShipperID FROM Shippers"
        insertcommand="INSERT INTO Shippers (CompanyName,Phone) VALUES (@CoName,@Phone)">
          <insertparameters>
            <asp:formparameter name="CoName" formfield="CompanyNameBox" />
            <asp:formparameter name="Phone"  formfield="PhoneBox" />
          </insertparameters>
      </asp:sqldatasource>

      <br /><asp:textbox
           id="CompanyNameBox"
           runat="server" />

      <asp:RequiredFieldValidator
        id="RequiredFieldValidator1"
        runat="server"
        ControlToValidate="CompanyNameBox"
        Display="Static"
        ErrorMessage="Please enter a company name." />

      <br /><asp:textbox
           id="PhoneBox"
           runat="server" />

      <asp:RequiredFieldValidator
        id="RequiredFieldValidator2"
        runat="server"
        ControlToValidate="PhoneBox"
        Display="Static"
        ErrorMessage="Please enter a phone number." />

      <br /><asp:button
           id="Button1"
           runat="server"
           text="Insert New Shipper"
           onclick="InsertShipper" />

    </form>
  </body>
</html>

다음 코드 예제에서는 SQL Server에서 데이터를 검색하고 컨트롤에 GridView 표시하는 방법과 컨트롤을 사용하여 DetailsView 컨트롤에서 GridView 선택한 행의 세부 정보를 확인하고 폼으로 새 레코드를 삽입하는 방법을 보여 줍니다.

처음에는 데이터가 컨트롤에 GridView 표시되고 선택한 행 GridView 도 컨트롤에 DetailsView 표시됩니다. 및 DetailsView 컨트롤은 GridView 서로 다른 데이터 원본 컨트롤을 사용합니다. 이 컨트롤과 DetailsView 연결된 컨트롤에는 FilterExpression 선택한 행이 표시되도록 하는 속성과 FilterParameters 해당 컨트롤 GridView 이 있습니다.

컨트롤 DetailsView 의 자동으로 생성된 삽입 단추를 DetailsView 클릭하면 새 레코드를 삽입하는 데 사용되는 다른 사용자 인터페이스가 표시됩니다. 이 예제에서는 저장 프로시저를 사용하여 레코드를 삽입하고 삽입된 행의 기본 키를 반환합니다. 레코드를 삽입하면 컬렉션이 DetailsView 바인딩된 열의 InsertParameters 값으로 자동으로 채워지고 메서드가 Insert 호출됩니다. ASP.NET DetailsView 양방향 데이터 바인딩 구문을 사용할 때 개체와 개체의 매개 변수에서 올바른 매개 변수 BoundFieldTemplateField 를 유추할 수 있습니다. 이 예제에서는 저장 프로시저에서 OnInserting 반환되는 기본 키를 처리하기 위해 이벤트 처리기에 추가 매개 변수가 추가됩니다.

마지막으로, 컨트롤 OnInserted 에 의해 데이터베이스에 DetailsView 데이터를 삽입한 후 이벤트 처리기가 호출되어 이벤트를 처리 Inserted 하고 삽입된 행의 기본 키 값이 표시되고 DataBind 컨트롤 메서드 GridView 가 명시적으로 호출되어 데이터를 새로 고칩니다.

<%@Page  Language="C#" %>
<%@Import Namespace="System.Data" %>
<%@Import Namespace="System.Data.Common" %>
<%@Import Namespace="System.Data.SqlClient" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
 private void On_Inserting(Object sender, SqlDataSourceCommandEventArgs e) {

    SqlParameter insertedKey = new SqlParameter("@PK_New", SqlDbType.Int);
    insertedKey.Direction    = ParameterDirection.Output;        
    e.Command.Parameters.Add(insertedKey);
 }

 private void On_Inserted(Object sender, SqlDataSourceStatusEventArgs e) {
    DbCommand command = e.Command;    
    
    // The label displays the primary key of the recently inserted row.
    Label1.Text = command.Parameters["@PK_New"].Value.ToString();
    
    // Force a refresh after the data is inserted.
    GridView1.DataBind();
 }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" runat="server">

      <asp:GridView
        id="GridView1"
        runat="server"
        AutoGenerateColumns="False"
        DataKeyNames="EmployeeID"        
        DataSourceID="SqlDataSource1">
        <columns>          
          <asp:BoundField HeaderText="First Name" DataField="FirstName" />
          <asp:BoundField HeaderText="Last Name" DataField="LastName" />
          <asp:BoundField HeaderText="Title" DataField="Title" />
          <asp:ButtonField ButtonType="Link" CommandName="Select" Text="Details..." />
        </columns>
      </asp:GridView>

      <asp:SqlDataSource
        id="SqlDataSource1"
        runat="server"
        ConnectionString="<%$ ConnectionStrings:MyNorthwind %>"
        SelectCommand="SELECT EmployeeID,FirstName,LastName,Title FROM Employees">
      </asp:SqlDataSource>

      <hr />

      <asp:DetailsView
        id="DetailsView1"
        runat="server"
        DataSourceID="SqlDataSource2"
        AutoGenerateRows="False"
        AutoGenerateInsertButton="True">
        <fields>
          <asp:BoundField HeaderText="First Name" DataField="FirstName" ReadOnly="False"/>
          <asp:BoundField HeaderText="Last Name" DataField="LastName" ReadOnly="False"/>
          <asp:TemplateField HeaderText="Title">
            <ItemTemplate>
              <asp:DropDownList
                id="TitleDropDownList"
                runat="server"
                selectedvalue="<%# Bind('Title') %>" >
                <asp:ListItem Selected="True">Sales Representative</asp:ListItem>
                <asp:ListItem>Sales Manager</asp:ListItem>
                <asp:ListItem>Vice President, Sales</asp:ListItem>
              </asp:DropDownList>
            </ItemTemplate>
          </asp:TemplateField>
          <asp:BoundField HeaderText="Notes" DataField="Notes" ReadOnly="False"/>
        </fields>
      </asp:DetailsView>


      <asp:SqlDataSource
        id="SqlDataSource2"
        runat="server"
        ConnectionString="<%$ ConnectionStrings:MyNorthwind%>"
        SelectCommand="SELECT * FROM Employees"
        InsertCommandType = "StoredProcedure"
        InsertCommand="sp_insertemployee"        
        OnInserting="On_Inserting"
        OnInserted ="On_Inserted"
        FilterExpression="EmployeeID={0}">
        <FilterParameters>
          <asp:ControlParameter Name="EmployeeID" ControlId="GridView1" PropertyName="SelectedValue" />
        </FilterParameters>
      </asp:SqlDataSource>

<!-- 
     -- An example sp_insertemployee stored procedure that returns
     -- the primary key of the row that was inserted in an OUT parameter.
     CREATE PROCEDURE sp_insertemployee 
        @FirstName nvarchar(10), 
        @LastName nvarchar(20) , 
        @Title nvarchar(30), 
        @Notes nvarchar(200), 
        @PK_New int OUTPUT
      AS
        INSERT INTO Employees(FirstName,LastName,Title,Notes)VALUES (@FirstName,@LastName,@Title,@Notes)
        SELECT @PK_New = @@IDENTITY
        RETURN (1)    
      GO
-->      

      <asp:Label 
        id="Label1"
        runat="server" />
      
    </form>
  </body>
</html>
<%@Page  Language="VB" %>
<%@Import Namespace="System.Data" %>
<%@Import Namespace="System.Data.Common" %>
<%@Import Namespace="System.Data.SqlClient" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

 Sub On_Inserting(ByVal sender As Object, ByVal e As SqlDataSourceCommandEventArgs)

    Dim insertedKey As SqlParameter  
    insertedKey = New SqlParameter("@PK_New", SqlDbType.Int)
    insertedKey.Direction    = ParameterDirection.Output     
    
    e.Command.Parameters.Add(insertedKey)

 End Sub 'On_Inserting

 Sub On_Inserted(ByVal sender As Object, ByVal e As SqlDataSourceStatusEventArgs)
    Dim command As DbCommand 
    command = e.Command
    
    ' The label displays the primary key of the recently inserted row.
    Label1.Text = command.Parameters("@PK_New").Value.ToString()    
    
    ' Explicitly call DataBind to refresh the data
    ' and show the newly inserted row.
    GridView1.DataBind()
 End Sub 'On_Inserted

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" runat="server">

      <asp:GridView
        id="GridView1"
        runat="server"
        AutoGenerateColumns="False"
        DataKeyNames="EmployeeID"        
        DataSourceID="SqlDataSource1">
        <columns>          
          <asp:BoundField HeaderText="First Name" DataField="FirstName" />
          <asp:BoundField HeaderText="Last Name" DataField="LastName" />
          <asp:BoundField HeaderText="Title" DataField="Title" />
          <asp:ButtonField ButtonType="Link" CommandName="Select" Text="Details..." />
        </columns>
      </asp:GridView>

      <asp:SqlDataSource
        id="SqlDataSource1"
        runat="server"
        ConnectionString="<%$ ConnectionStrings:MyNorthwind %>"
        SelectCommand="SELECT EmployeeID,FirstName,LastName,Title FROM Employees">
      </asp:SqlDataSource>

      <hr />

      <asp:DetailsView
        id="DetailsView1"
        runat="server"
        DataSourceID="SqlDataSource2"
        AutoGenerateRows="False"
        AutoGenerateInsertButton="True">
        <fields>
          <asp:BoundField HeaderText="First Name" DataField="FirstName" ReadOnly="False"/>
          <asp:BoundField HeaderText="Last Name" DataField="LastName" ReadOnly="False"/>
          <asp:TemplateField HeaderText="Title">
            <ItemTemplate>
              <asp:DropDownList
                id="TitleDropDownList"
                runat="server"
                selectedvalue="<%# Bind('Title') %>" >
                <asp:ListItem Selected="True">Sales Representative</asp:ListItem>
                <asp:ListItem>Sales Manager</asp:ListItem>
                <asp:ListItem>Vice President, Sales</asp:ListItem>
              </asp:DropDownList>
            </ItemTemplate>
          </asp:TemplateField>
          <asp:BoundField HeaderText="Notes" DataField="Notes" ReadOnly="False"/>
        </fields>
      </asp:DetailsView>


      <asp:SqlDataSource
        id="SqlDataSource2"
        runat="server"
        ConnectionString="<%$ ConnectionStrings:MyNorthwind%>"
        SelectCommand="SELECT * FROM Employees"
        InsertCommandType = "StoredProcedure"
        InsertCommand="sp_insertemployee"        
        OnInserting="On_Inserting"
        OnInserted ="On_Inserted"
        FilterExpression="EmployeeID={0}">
        <FilterParameters>
          <asp:ControlParameter Name="EmployeeID" ControlId="GridView1" PropertyName="SelectedValue" />
        </FilterParameters>
      </asp:SqlDataSource>

<!-- 
     -- An example sp_insertemployee stored procedure that returns
     -- the primary key of the row that was inserted in an OUT parameter.
     CREATE PROCEDURE sp_insertemployee 
        @FirstName nvarchar(10), 
        @LastName nvarchar(20) , 
        @Title nvarchar(30), 
        @Notes nvarchar(200), 
        @PK_New int OUTPUT
      AS
        INSERT INTO Employees(FirstName,LastName,Title,Notes)VALUES (@FirstName,@LastName,@Title,@Notes)
        SELECT @PK_New = @@IDENTITY
        RETURN (1)    
      GO
-->      

      <asp:Label 
        id="Label1"
        runat="server" />
      
    </form>
  </body>
</html>

설명

SQL InsertCommand 쿼리 또는 저장 프로시저의 이름을 나타내며 메서드에서 Insert 사용됩니다.

다른 데이터베이스 제품은 다양한 종류의 SQL을 사용하므로 SQL 문자열의 구문은 사용 중인 현재 ADO.NET 공급자에 따라 달라지며, 이 구문은 속성으로 ProviderName 식별됩니다. SQL 문자열이 매개 변수가 있는 쿼리 또는 명령인 경우 매개 변수의 자리 표시자도 사용 중인 ADO.NET 공급자에 따라 달라집니다. 예를 들어 공급자가 클래스의 System.Data.SqlClient기본 공급자 SqlDataSource 인 경우 매개 변수의 자리 표시자는 다음과 같습니다 '@parameterName'. 그러나 공급자가 orSystem.Data.OleDbSystem.Data.Odbc 설정된 경우 매개 변수의 자리 표시자는 .입니다'?'. 매개 변수가 있는 SQL 쿼리 및 명령에 대한 자세한 내용은 SqlDataSource 컨트롤에서 매개 변수 사용을 참조하세요.

InsertCommand 데이터 원본이 저장 프로시저를 지원하는 경우 SQL 문자열 또는 저장 프로시저의 이름이 될 수 있습니다.

이 속성은 InsertCommand 컨트롤과 연결된 속성 SqlDataSourceViewSqlDataSource 위임됩니다.

중요합니다

보안을 위해 속성이 InsertCommand 저장되지 않은 것은 뷰 상태입니다. 클라이언트에서 뷰 상태의 내용을 디코딩할 수 있으므로 데이터베이스 구조에 대한 중요한 정보를 뷰 상태에 저장하면 정보 공개 취약성이 발생할 수 있습니다.

중요합니다

값은 유효성 검사 없이 매개 변수에 삽입되며 이는 잠재적인 보안 위협입니다. 쿼리를 Filtering 실행하기 전에 이벤트를 사용하여 매개 변수 값의 유효성을 검사합니다. 자세한 내용은 스크립트 악용 개요를 참조하세요.

적용 대상

추가 정보