SqlDataSource.Insert Metodo

Definizione

Esegue un'operazione di inserimento utilizzando la stringa SQL InsertCommand e tutti i parametri nell'insieme InsertParameters.

public:
 int Insert();
public int Insert ();
member this.Insert : unit -> int
Public Function Insert () As Integer

Restituisce

Valore che rappresenta il numero di righe inserite nel database sottostante.

Eccezioni

L'oggetto SqlDataSource non può stabilire una connessione con l'origine dati sottostante.

Esempio

Nell'esempio di codice seguente viene illustrato come inserire dati in un database usando il SqlDataSource controllo e una semplice pagina di Web Forms. I dati correnti nella tabella Dati vengono visualizzati nel DropDownList controllo . È possibile aggiungere nuovi record immettendo i valori nei TextBox controlli e quindi facendo clic sul pulsante Inserisci . Quando si fa clic sul pulsante Inserisci , i valori specificati vengono inseriti nel database e quindi DropDownList viene aggiornato.

Importante

Questo esempio include una casella di testo che accetta l'input dell'utente, ovvero una potenziale minaccia per la sicurezza e i valori vengono inseriti in parametri senza convalida, che è anche una potenziale minaccia per la sicurezza. Usare l'evento Inserting per convalidare i valori dei parametri prima di eseguire la query. Per altre informazioni, vedere Cenni preliminari sugli attacchi tramite script.

Nota

Questo esempio illustra come usare la sintassi dichiarativa per l'accesso ai dati. Per informazioni su come accedere ai dati usando codice anziché markup, vedere Accesso ai dati in Visual Studio.

<%@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>

Commenti

Prima di eseguire l'operazione di inserimento, viene chiamato il OnInserting metodo per generare l'evento Inserting . È possibile gestire questo evento per esaminare i valori dei parametri e per eseguire qualsiasi pre-elaborazione prima dell'operazione Insert . Per eseguire un'operazione di inserimento, l'oggetto SqlDataSourceView compila un DbCommand oggetto usando il InsertCommand testo e le proprietà associate InsertParameters e quindi esegue l'oggetto DbCommand sul database sottostante.

Al termine dell'operazione, viene chiamato il OnInserted metodo per generare l'evento Inserted . È possibile gestire questo evento per esaminare i valori restituiti e i codici di errore e per eseguire qualsiasi post-elaborazione.

Il Insert metodo viene fornito per l'accesso a livello di codice al Insert metodo . Se il SqlDataSource controllo è associato a un controllo associato a dati, il controllo associato a dati chiama automaticamente il Insert metodo .

Il Insert metodo delega al Insert metodo dell'oggetto SqlDataSourceView associato al SqlDataSource controllo .

Importante

I valori vengono inseriti in parametri senza convalida, ovvero una potenziale minaccia per la sicurezza. Usare l'evento Filtering per convalidare i valori dei parametri prima di eseguire la query. Per altre informazioni, vedere Cenni preliminari sugli attacchi tramite script.

Si applica a

Vedi anche