SqlDataSource.InsertCommand プロパティ
定義
重要
一部の情報は、リリース前に大きく変更される可能性があるプレリリースされた製品に関するものです。 Microsoft は、ここに記載されている情報について、明示または黙示を問わず、一切保証しません。
基になるデータベースにデータを挿入するために 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 Forms ページをSqlDataSource使用してデータベースにデータを挿入する方法を示します。 2 番目のコード例では、Microsoft SQL Serverからデータを取得してコントロールにGridView表示する方法と、コントロールを使用DetailsViewして、選択した行の詳細をコントロールにGridView表示し、フォームとして新しいレコードを挿入する方法を示します。
Note
これらの例では、データ アクセスに宣言構文を使用する方法を示します。 マークアップではなくコードを使用してデータにアクセスする方法については、「 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 呼び出します。 は DetailsView 、ASP.NET 双方向データ バインディング構文が使用されている場合に、任意 BoundField のオブジェクトから正しいパラメーターと、 オブジェクトのパラメーター TemplateField を推論できます。 この例では、ストアド プロシージャによって返される主キーを 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.OleDbにSystem.Data.Odbc設定されている場合、 パラメーターのプレースホルダーは です'?'
。 パラメーター化された SQL クエリとコマンドの詳細については、「 SqlDataSource コントロールでのパラメーターの使用」を参照してください。
InsertCommandデータ ソースでストアド プロシージャがサポートされている場合は、SQL 文字列またはストアド プロシージャの名前を指定できます。
このプロパティは、 コントロールに InsertCommand 関連付けられている の SqlDataSourceView プロパティに SqlDataSource 委任します。
重要
セキュリティ上の理由から、 InsertCommand プロパティが格納されていないのはビュー ステートです。 クライアントでビュー ステートの内容をデコードできるため、データベース構造に関する機密情報をビュー ステートに格納すると、情報漏えいの脆弱性が発生する可能性があります。
重要
値は検証なしでパラメーターに挿入されます。これは、セキュリティ上の脅威になる可能性があります。 イベントを Filtering 使用して、クエリを実行する前にパラメーター値を検証します。 詳細については、「スクリプトによる攻略の概要」を参照してください。
適用対象
こちらもご覧ください
.NET
フィードバック
https://aka.ms/ContentUserFeedback」を参照してください。
以下は間もなく提供いたします。2024 年を通じて、コンテンツのフィードバック メカニズムとして GitHub の issue を段階的に廃止し、新しいフィードバック システムに置き換えます。 詳細については、「フィードバックの送信と表示