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 字符串。
示例
本部分包含两个代码示例。 第一个代码示例演示如何使用 SqlDataSource 控件和简单的Web Forms页将数据插入数据库。 第二个代码示例演示如何从 Microsoft SQL Server检索数据并将其显示在 控件中GridView,以及如何使用 DetailsView 控件查看控件中GridView所选行的详细信息,以及如何作为窗体插入新记录。
注意
这些示例演示如何使用声明性语法进行数据访问。 有关如何使用代码而不是标记访问数据的信息,请参阅 在 Visual Studio 中访问数据。
下面的代码示例演示如何使用 SqlDataSource 控件和简单的Web Forms页将数据插入数据库。 “数据表”中的当前数据显示在 控件中 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 。 GridView和 DetailsView 控件使用不同的数据源控件;与 DetailsView 关联的控件具有 FilterExpression 和 FilterParameters 属性,这可确保显示 的GridView选定行。
如果单击控件的自动生成的DetailsView“插入”按钮, DetailsView 将显示用于插入新记录的不同用户界面。 该示例使用存储过程插入记录并返回插入行的主键。 如果插入记录, DetailsView 将自动使用绑定列中的值填充 InsertParameters 集合,并调用 Insert 方法。 在使用 ASP.NET 双向数据绑定语法时, DetailsView 可以从任何 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.Odbc 或 System.Data.OleDb,则参数的占位符为 '?'
。 有关参数化 SQL 查询和命令的详细信息,请参阅 在 SqlDataSource 控件中使用参数。
InsertCommand可以是 SQL 字符串,也可以是存储过程的名称(如果数据源支持存储过程)。
此属性委托给InsertCommand与控件关联的 SqlDataSource 的 SqlDataSourceView 属性。
重要
出于安全目的, InsertCommand 不存储属性为视图状态。 由于可以在客户端上解码视图状态的内容,因此在视图状态中存储有关数据库结构的敏感信息可能会导致信息泄露漏洞。
适用于
另请参阅
反馈
https://aka.ms/ContentUserFeedback。
即将发布:在整个 2024 年,我们将逐步淘汰作为内容反馈机制的“GitHub 问题”,并将其取代为新的反馈系统。 有关详细信息,请参阅:提交和查看相关反馈