次の方法で共有


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 文字列。

このセクションには、2 つのコード例が含まれています。 最初のコード例では、 コントロールと単純な Web フォーム ページを使用して SqlDataSource データベースにデータを挿入する方法を示します。 2 番目のコード例では、Microsoft SQL Server からデータを取得してコントロールに GridView 表示する方法と、コントロールを使用 DetailsView して選択した行の詳細をコントロールに GridView 表示し、フォームとして新しいレコードを挿入する方法を示します。

注意

これらの例では、データ アクセスに宣言構文を使用する方法を示します。 マークアップではなくコードを使用してデータにアクセスする方法については、「 Visual Studio でのデータへのアクセス」を参照してください。

次のコード例では、 コントロールと単純な Web フォーム ページを使用して 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 。 はDetailsView、ASP.NET 双方向データ バインディング構文を使用する場合にTemplateField、任意BoundFieldのオブジェクトから正しいパラメーターと オブジェクトのパラメーターを推論できます。 この例では、ストアド プロシージャによって返される主キーを OnInserting 処理するために、イベント ハンドラーにパラメーターを追加します。

最後に、コントロールによって DetailsView データがデータベースに挿入されると、 OnInserted イベントを処理 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>

注釈

InsertCommand SQL クエリまたはストアド プロシージャの名前を表し、 メソッドによって Insert 使用されます。

データベース製品ごとに使用する SQL が異なるため、SQL 文字列の構文は、現在使用している ADO.NET プロバイダーによって決まります。これは、ProviderName プロパティから識別できます。 SQL 文字列がパラメーター化されたクエリまたはコメントである場合は、パラメーターのプレースホルダーも現在使用している ADO.NET プロバイダーによって決まります。 たとえば、プロバイダーが クラスの System.Data.SqlClient既定のプロバイダー SqlDataSource である である場合、パラメーターのプレースホルダーは です '@parameterName'。 ただし、プロバイダーが または System.Data.OleDbSystem.Data.Odbc設定されている場合、パラメーターのプレースホルダーは です'?'。 パラメーター化された SQL クエリとコマンドの詳細については、「 SqlDataSource コントロールでのパラメーターの使用」を参照してください。

InsertCommandデータ ソースでストアド プロシージャがサポートされている場合は、SQL 文字列またはストアド プロシージャの名前を指定できます。

このプロパティは、 コントロールに InsertCommand 関連付けられている の SqlDataSourceView プロパティに委任します SqlDataSource

重要

セキュリティ上の理由から、 InsertCommand プロパティはビュー ステートとして格納されません。 クライアントでビュー ステートの内容をデコードできるため、データベース構造に関する機密情報をビュー ステートに格納すると、情報漏えいの脆弱性が発生する可能性があります。

重要

値は検証なしでパラメーターに挿入されます。これは、潜在的なセキュリティ上の脅威です。 イベントを Filtering 使用して、クエリを実行する前にパラメーター値を検証します。 詳細については、「スクリプトによる攻略の概要」を参照してください。

適用対象

こちらもご覧ください