Condividi tramite


SqlCommand Classe

Definizione

Rappresenta un'istruzione Transact-SQL o una stored procedure da eseguire su un database di SQL Server. Questa classe non può essere ereditata.

public ref class SqlCommand sealed : System::Data::Common::DbCommand
public ref class SqlCommand sealed : System::ComponentModel::Component, ICloneable, IDisposable, System::Data::IDbCommand
public ref class SqlCommand sealed : System::Data::Common::DbCommand, ICloneable
public sealed class SqlCommand : System.Data.Common.DbCommand
public sealed class SqlCommand : System.ComponentModel.Component, ICloneable, IDisposable, System.Data.IDbCommand
public sealed class SqlCommand : System.Data.Common.DbCommand, ICloneable
type SqlCommand = class
    inherit DbCommand
type SqlCommand = class
    inherit Component
    interface IDbCommand
    interface IDisposable
    interface ICloneable
type SqlCommand = class
    inherit DbCommand
    interface ICloneable
Public NotInheritable Class SqlCommand
Inherits DbCommand
Public NotInheritable Class SqlCommand
Inherits Component
Implements ICloneable, IDbCommand, IDisposable
Public NotInheritable Class SqlCommand
Inherits DbCommand
Implements ICloneable
Ereditarietà
SqlCommand
Ereditarietà
Ereditarietà
Implementazioni

Esempio

Nell'esempio seguente viene creato un oggetto SqlConnection, un SqlCommandoggetto e un oggetto SqlDataReader. L'esempio legge i dati, scrivendoli nella console. Infine, l'esempio chiude SqlDataReader e quindi quando SqlConnection esce dai blocchi di Using codice.

private static void ReadOrderData(string connectionString)
{
    string queryString =
        "SELECT OrderID, CustomerID FROM dbo.Orders;";
    using (SqlConnection connection = new SqlConnection(
               connectionString))
    {
        SqlCommand command = new SqlCommand(
            queryString, connection);
        connection.Open();
        using(SqlDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                Console.WriteLine(String.Format("{0}, {1}",
                    reader[0], reader[1]));
            }
        }
    }
}
Public Sub ReadOrderData(ByVal connectionString As String)
    Dim queryString As String = _
        "SELECT OrderID, CustomerID FROM dbo.Orders;"
    Using connection As New SqlConnection(connectionString)
        Dim command As New SqlCommand(queryString, connection)
        connection.Open()
        Dim reader As SqlDataReader = command.ExecuteReader()
        Try
            While reader.Read()
                Console.WriteLine(String.Format("{0}, {1}", _
                    reader(0), reader(1)))
            End While
        Finally
            ' Always call Close when done reading.
            reader.Close()
        End Try
    End Using
End Sub

Nell'esempio seguente viene illustrato come creare ed eseguire tipi diversi di oggetti SqlCommand.

Prima di tutto è necessario creare il database di esempio eseguendo lo script seguente:

USE [master]
GO

CREATE DATABASE [MySchool]
GO

USE [MySchool]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[CourseExtInfo] @CourseId int
as
select c.CourseID,c.Title,c.Credits,d.Name as DepartmentName
from Course as c left outer join Department as d on c.DepartmentID=d.DepartmentID
where c.CourseID=@CourseId

GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create procedure [dbo].[DepartmentInfo] @DepartmentId int,@CourseCount int output
as
select @CourseCount=Count(c.CourseID)
from course as c
where c.DepartmentID=@DepartmentId

select d.DepartmentID,d.Name,d.Budget,d.StartDate,d.Administrator
from Department as d
where d.DepartmentID=@DepartmentId

GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[GetDepartmentsOfSpecifiedYear]
@Year int,@BudgetSum money output
AS
BEGIN
        SELECT @BudgetSum=SUM([Budget])
  FROM [MySchool].[dbo].[Department]
  Where YEAR([StartDate])=@Year

SELECT [DepartmentID]
      ,[Name]
      ,[Budget]
      ,[StartDate]
      ,[Administrator]
  FROM [MySchool].[dbo].[Department]
  Where YEAR([StartDate])=@Year

END
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Course]([CourseID] [nvarchar](10) NOT NULL,
[Year] [smallint] NOT NULL,
[Title] [nvarchar](100) NOT NULL,
[Credits] [int] NOT NULL,
[DepartmentID] [int] NOT NULL,
 CONSTRAINT [PK_Course] PRIMARY KEY CLUSTERED
(
[CourseID] ASC,
[Year] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]

GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Department]([DepartmentID] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NOT NULL,
[Budget] [money] NOT NULL,
[StartDate] [datetime] NOT NULL,
[Administrator] [int] NULL,
 CONSTRAINT [PK_Department] PRIMARY KEY CLUSTERED
(
[DepartmentID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]

GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Person]([PersonID] [int] IDENTITY(1,1) NOT NULL,
[LastName] [nvarchar](50) NOT NULL,
[FirstName] [nvarchar](50) NOT NULL,
[HireDate] [datetime] NULL,
[EnrollmentDate] [datetime] NULL,
 CONSTRAINT [PK_School.Student] PRIMARY KEY CLUSTERED
(
[PersonID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]

GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[StudentGrade]([EnrollmentID] [int] IDENTITY(1,1) NOT NULL,
[CourseID] [nvarchar](10) NOT NULL,
[StudentID] [int] NOT NULL,
[Grade] [decimal](3, 2) NOT NULL,
 CONSTRAINT [PK_StudentGrade] PRIMARY KEY CLUSTERED
(
[EnrollmentID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]

GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create view [dbo].[EnglishCourse]
as
select c.CourseID,c.Title,c.Credits,c.DepartmentID
from Course as c join Department as d on c.DepartmentID=d.DepartmentID
where d.Name=N'English'

GO
INSERT [dbo].[Course] ([CourseID], [Year], [Title], [Credits], [DepartmentID]) VALUES (N'C1045', 2012, N'Calculus', 4, 7)
INSERT [dbo].[Course] ([CourseID], [Year], [Title], [Credits], [DepartmentID]) VALUES (N'C1061', 2012, N'Physics', 4, 1)
INSERT [dbo].[Course] ([CourseID], [Year], [Title], [Credits], [DepartmentID]) VALUES (N'C2021', 2012, N'Composition', 3, 2)
INSERT [dbo].[Course] ([CourseID], [Year], [Title], [Credits], [DepartmentID]) VALUES (N'C2042', 2012, N'Literature', 4, 2)
SET IDENTITY_INSERT [dbo].[Department] ON

INSERT [dbo].[Department] ([DepartmentID], [Name], [Budget], [StartDate], [Administrator]) VALUES (1, N'Engineering', 350000.0000, CAST(0x0000999C00000000 AS DateTime), 2)
INSERT [dbo].[Department] ([DepartmentID], [Name], [Budget], [StartDate], [Administrator]) VALUES (2, N'English', 120000.0000, CAST(0x0000999C00000000 AS DateTime), 6)
INSERT [dbo].[Department] ([DepartmentID], [Name], [Budget], [StartDate], [Administrator]) VALUES (4, N'Economics', 200000.0000, CAST(0x0000999C00000000 AS DateTime), 4)
INSERT [dbo].[Department] ([DepartmentID], [Name], [Budget], [StartDate], [Administrator]) VALUES (7, N'Mathematics', 250024.0000, CAST(0x0000999C00000000 AS DateTime), 3)
SET IDENTITY_INSERT [dbo].[Department] OFF
SET IDENTITY_INSERT [dbo].[Person] ON

INSERT [dbo].[Person] ([PersonID], [LastName], [FirstName], [HireDate], [EnrollmentDate]) VALUES (1, N'Hu', N'Nan', NULL, CAST(0x0000A0BF00000000 AS DateTime))
INSERT [dbo].[Person] ([PersonID], [LastName], [FirstName], [HireDate], [EnrollmentDate]) VALUES (2, N'Norman', N'Laura', NULL, CAST(0x0000A0BF00000000 AS DateTime))
INSERT [dbo].[Person] ([PersonID], [LastName], [FirstName], [HireDate], [EnrollmentDate]) VALUES (3, N'Olivotto', N'Nino', NULL, CAST(0x0000A0BF00000000 AS DateTime))
INSERT [dbo].[Person] ([PersonID], [LastName], [FirstName], [HireDate], [EnrollmentDate]) VALUES (4, N'Anand', N'Arturo', NULL, CAST(0x0000A0BF00000000 AS DateTime))
INSERT [dbo].[Person] ([PersonID], [LastName], [FirstName], [HireDate], [EnrollmentDate]) VALUES (5, N'Jai', N'Damien', NULL, CAST(0x0000A0BF00000000 AS DateTime))
INSERT [dbo].[Person] ([PersonID], [LastName], [FirstName], [HireDate], [EnrollmentDate]) VALUES (6, N'Holt', N'Roger', CAST(0x000097F100000000 AS DateTime), NULL)
INSERT [dbo].[Person] ([PersonID], [LastName], [FirstName], [HireDate], [EnrollmentDate]) VALUES (7, N'Martin', N'Randall', CAST(0x00008B1A00000000 AS DateTime), NULL)
SET IDENTITY_INSERT [dbo].[Person] OFF
SET IDENTITY_INSERT [dbo].[StudentGrade] ON

INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (1, N'C1045', 1, CAST(3.50 AS Decimal(3, 2)))
INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (2, N'C1045', 2, CAST(3.00 AS Decimal(3, 2)))
INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (3, N'C1045', 3, CAST(2.50 AS Decimal(3, 2)))
INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (4, N'C1045', 4, CAST(4.00 AS Decimal(3, 2)))
INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (5, N'C1045', 5, CAST(3.50 AS Decimal(3, 2)))
INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (6, N'C1061', 1, CAST(4.00 AS Decimal(3, 2)))
INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (7, N'C1061', 3, CAST(3.50 AS Decimal(3, 2)))
INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (8, N'C1061', 4, CAST(2.50 AS Decimal(3, 2)))
INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (9, N'C1061', 5, CAST(1.50 AS Decimal(3, 2)))
INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (10, N'C2021', 1, CAST(2.50 AS Decimal(3, 2)))
INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (11, N'C2021', 2, CAST(3.50 AS Decimal(3, 2)))
INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (12, N'C2021', 4, CAST(3.00 AS Decimal(3, 2)))
INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (13, N'C2021', 5, CAST(3.00 AS Decimal(3, 2)))
INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (14, N'C2042', 1, CAST(2.00 AS Decimal(3, 2)))
INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (15, N'C2042', 2, CAST(3.50 AS Decimal(3, 2)))
INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (16, N'C2042', 3, CAST(4.00 AS Decimal(3, 2)))
INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (17, N'C2042', 5, CAST(3.00 AS Decimal(3, 2)))
SET IDENTITY_INSERT [dbo].[StudentGrade] OFF
ALTER TABLE [dbo].[Course]  WITH CHECK ADD  CONSTRAINT [FK_Course_Department] FOREIGN KEY([DepartmentID])
REFERENCES [dbo].[Department] ([DepartmentID])
GO
ALTER TABLE [dbo].[Course] CHECK CONSTRAINT [FK_Course_Department]
GO
ALTER TABLE [dbo].[StudentGrade]  WITH CHECK ADD  CONSTRAINT [FK_StudentGrade_Student] FOREIGN KEY([StudentID])
REFERENCES [dbo].[Person] ([PersonID])
GO
ALTER TABLE [dbo].[StudentGrade] CHECK CONSTRAINT [FK_StudentGrade_Student]
GO

Compilare ed eseguire quindi quanto segue:

using System;
using System.Data;
using System.Data.SqlClient;
using System.Threading.Tasks;

class Program {

   static class SqlHelper {
      // Set the connection, command, and then execute the command with non query.
      public static Int32 ExecuteNonQuery(String connectionString, String commandText,
          CommandType commandType, params SqlParameter[] parameters) {
         using (SqlConnection conn = new SqlConnection(connectionString)) {
            using (SqlCommand cmd = new SqlCommand(commandText, conn)) {
               // There're three command types: StoredProcedure, Text, TableDirect. The TableDirect
               // type is only for OLE DB.
               cmd.CommandType = commandType;
               cmd.Parameters.AddRange(parameters);

               conn.Open();
               return cmd.ExecuteNonQuery();
            }
         }
      }

      // Set the connection, command, and then execute the command and only return one value.
      public static Object ExecuteScalar(String connectionString, String commandText,
          CommandType commandType, params SqlParameter[] parameters) {
         using (SqlConnection conn = new SqlConnection(connectionString)) {
            using (SqlCommand cmd = new SqlCommand(commandText, conn)) {
               cmd.CommandType = commandType;
               cmd.Parameters.AddRange(parameters);

               conn.Open();
               return cmd.ExecuteScalar();
            }
         }
      }

      // Set the connection, command, and then execute the command with query and return the reader.
      public static SqlDataReader ExecuteReader(String connectionString, String commandText,
          CommandType commandType, params SqlParameter[] parameters) {
         SqlConnection conn = new SqlConnection(connectionString);

         using (SqlCommand cmd = new SqlCommand(commandText, conn)) {
            cmd.CommandType = commandType;
            cmd.Parameters.AddRange(parameters);

            conn.Open();
            // When using CommandBehavior.CloseConnection, the connection will be closed when the
            // IDataReader is closed.
            SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);

            return reader;
         }
      }
   }

   static void Main(string[] args) {
      String connectionString = "Data Source=(local);Initial Catalog=MySchool;Integrated Security=True;Asynchronous Processing=true;";

      CountCourses(connectionString, 2012);
      Console.WriteLine();

      Console.WriteLine("Following result is the departments that started from 2007:");
      GetDepartments(connectionString, 2007);
      Console.WriteLine();

      Console.WriteLine("Add the credits when the credits of course is lower than 4.");
      AddCredits(connectionString, 4);
      Console.WriteLine();

      Console.WriteLine("Please press any key to exit...");
      Console.ReadKey();
   }

   static void CountCourses(String connectionString, Int32 year) {
      String commandText = "Select Count([CourseID]) FROM [MySchool].[dbo].[Course] Where Year=@Year";
      SqlParameter parameterYear = new SqlParameter("@Year", SqlDbType.Int);
      parameterYear.Value = year;

      Object oValue = SqlHelper.ExecuteScalar(connectionString, commandText, CommandType.Text, parameterYear);
      Int32 count;
      if (Int32.TryParse(oValue.ToString(), out count))
         Console.WriteLine("There {0} {1} course{2} in {3}.", count > 1 ? "are" : "is", count, count > 1 ? "s" : null, year);
   }

   // Display the Departments that start from the specified year.
   static void GetDepartments(String connectionString, Int32 year) {
      String commandText = "dbo.GetDepartmentsOfSpecifiedYear";

      // Specify the year of StartDate
      SqlParameter parameterYear = new SqlParameter("@Year", SqlDbType.Int);
      parameterYear.Value = year;

      // When the direction of parameter is set as Output, you can get the value after
      // executing the command.
      SqlParameter parameterBudget = new SqlParameter("@BudgetSum", SqlDbType.Money);
      parameterBudget.Direction = ParameterDirection.Output;

      using (SqlDataReader reader = SqlHelper.ExecuteReader(connectionString, commandText,
          CommandType.StoredProcedure, parameterYear, parameterBudget)) {
         Console.WriteLine("{0,-20}{1,-20}{2,-20}{3,-20}", "Name", "Budget", "StartDate",
             "Administrator");
         while (reader.Read()) {
            Console.WriteLine("{0,-20}{1,-20:C}{2,-20:d}{3,-20}", reader["Name"],
                reader["Budget"], reader["StartDate"], reader["Administrator"]);
         }
      }
      Console.WriteLine("{0,-20}{1,-20:C}", "Sum:", parameterBudget.Value);
   }

   // If credits of course is lower than the certain value, the method will add the credits.
   static void AddCredits(String connectionString, Int32 creditsLow) {
      String commandText = "Update [MySchool].[dbo].[Course] Set Credits=Credits+1 Where Credits<@Credits";

      SqlParameter parameterCredits = new SqlParameter("@Credits", creditsLow);

      Int32 rows = SqlHelper.ExecuteNonQuery(connectionString, commandText, CommandType.Text, parameterCredits);

      Console.WriteLine("{0} row{1} {2} updated.", rows, rows > 1 ? "s" : null, rows > 1 ? "are" : "is");
   }
}

Commenti

Quando viene creata un'istanza di , le proprietà di SqlCommand lettura/scrittura vengono impostate sui valori iniziali. Per un elenco di questi valori, vedere il SqlCommand costruttore.

SqlCommand include i metodi seguenti per l'esecuzione di comandi in un database di SQL Server:

Elemento Descrizione
BeginExecuteNonQuery Avvia l'esecuzione asincrona dell'istruzione Transact-SQL o della stored procedure descritta da questo SqlCommand, in genere eseguendo comandi come le istruzioni INSERT, DELETE, UPDATE e SET. Ogni chiamata a BeginExecuteNonQuery deve essere associata a una chiamata a EndExecuteNonQuery, che termina l'operazione, in genere in un thread separato.
BeginExecuteReader Avvia l'esecuzione asincrona dell'istruzione Transact-SQL o della stored procedure descritta da questo SqlCommand oggetto e recupera uno o più set di risultati dal server. Ogni chiamata a BeginExecuteReader deve essere associata a una chiamata a EndExecuteReader, che termina l'operazione, in genere in un thread separato.
BeginExecuteXmlReader Avvia l'esecuzione asincrona dell'istruzione Transact-SQL o della stored procedure descritta da questo SqlCommandoggetto . Ogni chiamata a BeginExecuteXmlReader deve essere associata a una chiamata a EndExecuteXmlReader, che termina l'operazione, in genere in un thread separato e restituisce un XmlReader oggetto .
ExecuteReader Esegue i comandi che restituiscono righe. Per migliorare le prestazioni, ExecuteReader richiama i comandi usando la stored procedure di sistema Transact-SQL sp_executesql . Pertanto, ExecuteReader potrebbe non avere l'effetto desiderato se usato per eseguire comandi come Transact-SQL istruzioni SET.
ExecuteNonQuery Esegue comandi come Transact-SQL istruzioni INSERT, DELETE, UPDATE e SET.
ExecuteScalar Recupera un singolo valore , ad esempio un valore di aggregazione, da un database.
ExecuteXmlReader Invia all'oggetto CommandTextConnection e compila un XmlReader oggetto .

È possibile reimpostare la CommandText proprietà e riutilizzare l'oggetto SqlCommand . Tuttavia, è necessario chiudere prima SqlDataReader di poter eseguire un comando nuovo o precedente.

Se un SqlException oggetto viene generato dal metodo che esegue un SqlCommandoggetto , rimane SqlConnection aperto quando il livello di gravità è 19 o minore. Quando il livello di gravità è 20 o superiore, il server in genere chiude .SqlConnection Tuttavia, l'utente può riaprire la connessione e continuare.

Annotazioni

I parametri senza nome, detti anche ordinali, non sono supportati dal provider di dati .NET Framework per SQL Server.

Costruttori

Nome Descrizione
SqlCommand()

Inizializza una nuova istanza della classe SqlCommand.

SqlCommand(String, SqlConnection, SqlTransaction, SqlCommandColumnEncryptionSetting)

Inizializza una nuova istanza della SqlCommand classe con testo del comando, connessione, transazione e impostazione di crittografia specificati.

SqlCommand(String, SqlConnection, SqlTransaction)

Inizializza una nuova istanza della SqlCommand classe con il testo della query, un SqlConnectionoggetto e .SqlTransaction

SqlCommand(String, SqlConnection)

Inizializza una nuova istanza della SqlCommand classe con il testo della query e un oggetto SqlConnection.

SqlCommand(String)

Inizializza una nuova istanza della SqlCommand classe con il testo della query.

Proprietà

Nome Descrizione
CanRaiseEvents

Ottiene un valore che indica se il componente può generare un evento.

(Ereditato da Component)
ColumnEncryptionSetting

Ottiene o imposta l'impostazione di crittografia della colonna per questo comando.

CommandText

Ottiene o imposta l'istruzione Transact-SQL, il nome della tabella o la stored procedure da eseguire nell'origine dati.

CommandTimeout

Ottiene o imposta il tempo di attesa , espresso in secondi, prima di terminare il tentativo di eseguire un comando e generare un errore.

CommandType

Ottiene o imposta un valore che indica come deve essere interpretata la CommandText proprietà.

Connection

Ottiene o imposta l'oggetto SqlConnection utilizzato da questa istanza di SqlCommand.

Container

Ottiene l'oggetto IContainer contenente l'oggetto Component.

(Ereditato da Component)
DbConnection

Ottiene o imposta l'oggetto DbConnection utilizzato da questo DbCommandoggetto .

(Ereditato da DbCommand)
DbParameterCollection

Ottiene la raccolta di DbParameter oggetti .

(Ereditato da DbCommand)
DbTransaction

Ottiene o imposta l'oggetto all'interno del quale viene eseguito l'oggetto DbTransactionDbCommand .

(Ereditato da DbCommand)
DesignMode

Ottiene un valore che indica se è Component attualmente in modalità progettazione.

(Ereditato da Component)
DesignTimeVisible

Ottiene o imposta un valore che indica se l'oggetto comando deve essere visibile in un controllo Progettazione Windows Form.

Events

Ottiene l'elenco dei gestori eventi associati a questo Componentoggetto .

(Ereditato da Component)
Notification

Ottiene o imposta un valore che specifica l'oggetto SqlNotificationRequest associato a questo comando.

NotificationAutoEnlist

Ottiene o imposta un valore che indica se l'applicazione deve ricevere automaticamente notifiche di query da un oggetto comune SqlDependency .

Parameters

Ottiene l'oggetto SqlParameterCollection.

Site

Ottiene o imposta l'oggetto ISite dell'oggetto Component.

(Ereditato da Component)
Transaction

Ottiene o imposta l'oggetto all'interno del SqlTransaction quale viene eseguito l'oggetto SqlCommand .

UpdatedRowSource

Ottiene o imposta la DataRow modalità di applicazione dei risultati del comando a quando viene utilizzato dal metodo Update dell'oggetto DbDataAdapter.

Metodi

Nome Descrizione
BeginExecuteNonQuery()

Avvia l'esecuzione asincrona dell'istruzione Transact-SQL o della stored procedure descritta da questo SqlCommandoggetto .

BeginExecuteNonQuery(AsyncCallback, Object)

Avvia l'esecuzione asincrona dell'istruzione Transact-SQL o della stored procedure descritta da , SqlCommandin base a una routine di callback e informazioni sullo stato.

BeginExecuteReader()

Avvia l'esecuzione asincrona dell'istruzione Transact-SQL o della stored procedure descritta da questo SqlCommandoggetto e recupera uno o più set di risultati dal server.

BeginExecuteReader(AsyncCallback, Object, CommandBehavior)

Avvia l'esecuzione asincrona dell'istruzione Transact-SQL o della stored procedure descritta da , SqlCommandutilizzando uno dei valori e recuperando uno o più set di CommandBehavior risultati dal server, in base a una routine di callback e informazioni sullo stato.

BeginExecuteReader(AsyncCallback, Object)

Avvia l'esecuzione asincrona dell'istruzione Transact-SQL o della stored procedure descritta da questo SqlCommand oggetto e recupera uno o più set di risultati dal server, in base a una routine di callback e informazioni sullo stato.

BeginExecuteReader(CommandBehavior)

Avvia l'esecuzione asincrona dell'istruzione Transact-SQL o della stored procedure descritta da questo SqlCommand oggetto utilizzando uno dei CommandBehavior valori .

BeginExecuteXmlReader()

Avvia l'esecuzione asincrona dell'istruzione Transact-SQL o della stored procedure descritta da questo SqlCommand oggetto e restituisce i risultati come XmlReader oggetto .

BeginExecuteXmlReader(AsyncCallback, Object)

Avvia l'esecuzione asincrona dell'istruzione Transact-SQL o della stored procedure descritta da questo SqlCommand oggetto e restituisce i risultati come XmlReader oggetto utilizzando una routine di callback.

Cancel()

Tenta di annullare l'esecuzione di un oggetto SqlCommand.

Clone()

Crea un nuovo SqlCommand oggetto che rappresenta una copia dell'istanza corrente.

CreateDbParameter()

Crea una nuova istanza di un DbParameter oggetto .

(Ereditato da DbCommand)
CreateObjRef(Type)

Crea un oggetto che contiene tutte le informazioni pertinenti necessarie per generare un proxy utilizzato per comunicare con un oggetto remoto.

(Ereditato da MarshalByRefObject)
CreateParameter()

Crea una nuova istanza di un SqlParameter oggetto .

Dispose()

Esegue attività definite dall'applicazione associate alla liberazione, al rilascio o alla reimpostazione di risorse non gestite.

(Ereditato da DbCommand)
Dispose()

Rilascia tutte le risorse usate da Component.

(Ereditato da Component)
Dispose(Boolean)

Rilascia le risorse non gestite usate da DbCommand e, facoltativamente, rilascia le risorse gestite.

(Ereditato da DbCommand)
Dispose(Boolean)

Rilascia le risorse non gestite usate da Component e, facoltativamente, rilascia le risorse gestite.

(Ereditato da Component)
EndExecuteNonQuery(IAsyncResult)

Termina l'esecuzione asincrona di un'istruzione Transact-SQL.

EndExecuteReader(IAsyncResult)

Termina l'esecuzione asincrona di un'istruzione Transact-SQL, restituendo l'oggetto richiesto SqlDataReader.

EndExecuteXmlReader(IAsyncResult)

Termina l'esecuzione asincrona di un'istruzione Transact-SQL, restituendo i dati richiesti come XML.

Equals(Object)

Determina se l'oggetto specificato è uguale all'oggetto corrente.

(Ereditato da Object)
ExecuteDbDataReader(CommandBehavior)

Esegue il comando sulla connessione, restituendo un DbDataReader oggetto che può essere usato per accedere ai risultati.

(Ereditato da DbCommand)
ExecuteDbDataReaderAsync(CommandBehavior, CancellationToken)

I provider devono implementare questo metodo per fornire un'implementazione non predefinita per ExecuteReader gli overload.

L'implementazione predefinita richiama il metodo sincrono ExecuteReader() e restituisce un'attività completata, bloccando il thread chiamante. L'implementazione predefinita restituirà un'attività annullata se è stato passato un token di annullamento già annullato. Le eccezioni generate da ExecuteReader verranno comunicate tramite la proprietà Task Exception restituita.

Questo metodo accetta un token di annullamento che può essere usato per richiedere l'annullamento anticipato dell'operazione. Le implementazioni possono ignorare questa richiesta.

(Ereditato da DbCommand)
ExecuteNonQuery()

Esegue un'istruzione Transact-SQL sulla connessione e restituisce il numero di righe interessate.

ExecuteNonQueryAsync()

Versione asincrona di ExecuteNonQuery(), che esegue il comando sul relativo oggetto connessione, restituendo il numero di righe interessate.

ExecuteNonQueryAsync(CancellationToken) Richiama con CancellationToken.None.

(Ereditato da DbCommand)
ExecuteNonQueryAsync(CancellationToken)

Versione asincrona di ExecuteNonQuery(), che esegue un'istruzione Transact-SQL sulla connessione e restituisce il numero di righe interessate. Il token di annullamento può essere usato per richiedere che l'operazione venga abbandonata prima della scadenza del timeout del comando. Le eccezioni verranno segnalate tramite l'oggetto Task restituito.

ExecuteReader()

Invia all'oggetto CommandTextConnection e compila un oggetto SqlDataReader.

ExecuteReader(CommandBehavior)

Invia all'oggetto CommandTextConnectione compila un SqlDataReader oggetto utilizzando uno dei CommandBehavior valori .

ExecuteReaderAsync()

Versione asincrona di ExecuteReader(), che invia all'oggetto CommandTextConnection e compila un oggetto SqlDataReader. Le eccezioni verranno segnalate tramite l'oggetto Task restituito.

ExecuteReaderAsync(CancellationToken)

Versione asincrona di ExecuteReader(), che invia all'oggetto CommandTextConnection e compila un oggetto SqlDataReader.

Il token di annullamento può essere usato per richiedere che l'operazione venga abbandonata prima della scadenza del timeout del comando. Le eccezioni verranno segnalate tramite l'oggetto Task restituito.

ExecuteReaderAsync(CommandBehavior, CancellationToken)

Una versione asincrona di ExecuteReader(CommandBehavior), che invia l'oggetto CommandTextConnectiona e compila un oggetto SqlDataReader

Il token di annullamento può essere usato per richiedere che l'operazione venga abbandonata prima della scadenza del timeout del comando. Le eccezioni verranno segnalate tramite l'oggetto Task restituito.

ExecuteReaderAsync(CommandBehavior)

Una versione asincrona di ExecuteReader(CommandBehavior), che invia l'oggetto CommandTextConnectiona e compila un oggetto SqlDataReader. Le eccezioni verranno segnalate tramite l'oggetto Task restituito.

ExecuteScalar()

Esegue la query e restituisce la prima colonna della prima riga nel set di risultati restituito dalla query. Le colonne o le righe aggiuntive vengono ignorate.

ExecuteScalarAsync()

Versione asincrona di ExecuteScalar(), che esegue il comando e restituisce la prima colonna della prima riga del primo set di risultati restituito. Tutte le altre colonne, righe e set di risultati vengono ignorate.

ExecuteScalarAsync(CancellationToken) Richiama con CancellationToken.None.

(Ereditato da DbCommand)
ExecuteScalarAsync(CancellationToken)

Versione asincrona di , che esegue la query in modo asincrono e restituisce la prima colonna della prima riga nel set di ExecuteScalar()risultati restituito dalla query. Le colonne o le righe aggiuntive vengono ignorate.

Il token di annullamento può essere usato per richiedere che l'operazione venga abbandonata prima della scadenza del timeout del comando. Le eccezioni verranno segnalate tramite l'oggetto Task restituito.

ExecuteXmlReader()

Invia all'oggetto CommandTextConnection e compila un XmlReader oggetto .

ExecuteXmlReaderAsync()

Versione asincrona di ExecuteXmlReader(), che invia all'oggetto CommandTextConnection e compila un XmlReader oggetto .

Le eccezioni verranno segnalate tramite l'oggetto Task restituito.

ExecuteXmlReaderAsync(CancellationToken)

Versione asincrona di ExecuteXmlReader(), che invia all'oggetto CommandTextConnection e compila un XmlReader oggetto .

Il token di annullamento può essere usato per richiedere che l'operazione venga abbandonata prima della scadenza del timeout del comando. Le eccezioni verranno segnalate tramite l'oggetto Task restituito.

GetHashCode()

Funge da funzione hash predefinita.

(Ereditato da Object)
GetLifetimeService()
Obsoleti.

Recupera l'oggetto servizio di durata corrente che controlla i criteri di durata per questa istanza.

(Ereditato da MarshalByRefObject)
GetService(Type)

Restituisce un oggetto che rappresenta un servizio fornito da Component o da Container.

(Ereditato da Component)
GetType()

Ottiene il Type dell'istanza corrente.

(Ereditato da Object)
InitializeLifetimeService()
Obsoleti.

Ottiene un oggetto servizio di durata per controllare i criteri di durata per questa istanza.

(Ereditato da MarshalByRefObject)
MemberwiseClone()

Crea una copia superficiale del Objectcorrente.

(Ereditato da Object)
MemberwiseClone(Boolean)

Crea una copia superficiale dell'oggetto corrente MarshalByRefObject .

(Ereditato da MarshalByRefObject)
Prepare()

Crea una versione preparata del comando in un'istanza di SQL Server.

ResetCommandTimeout()

Reimposta il valore predefinito della CommandTimeout proprietà.

ToString()

Restituisce una stringa che rappresenta l'oggetto corrente.

(Ereditato da Object)
ToString()

Restituisce un oggetto String contenente il nome dell'oggetto Component, se presente. Questo metodo non deve essere sottoposto a override.

(Ereditato da Component)

Eventi

Nome Descrizione
Disposed

Si verifica quando il componente viene eliminato da una chiamata al Dispose() metodo .

(Ereditato da Component)
StatementCompleted

Si verifica quando viene completata l'esecuzione di un'istruzione Transact-SQL.

Implementazioni dell'interfaccia esplicita

Nome Descrizione
ICloneable.Clone()

Crea un nuovo SqlCommand oggetto che rappresenta una copia dell'istanza corrente.

IDbCommand.Connection

Ottiene o imposta l'oggetto IDbConnection utilizzato da questa istanza di IDbCommand.

(Ereditato da DbCommand)
IDbCommand.CreateParameter()

Crea una nuova istanza di un SqlParameter oggetto .

IDbCommand.CreateParameter()

Crea una nuova istanza di un IDbDataParameter oggetto .

(Ereditato da DbCommand)
IDbCommand.ExecuteReader()

Invia l'oggetto CommandTextConnectiona e compila un oggetto SqlDataReader.

IDbCommand.ExecuteReader()

Esegue l'oggetto sull'oggetto CommandTextConnection e compila un oggetto IDataReader.

(Ereditato da DbCommand)
IDbCommand.ExecuteReader(CommandBehavior)

Invia all'oggetto CommandTextConnectione compila un SqlDataReader oggetto utilizzando uno dei CommandBehavior valori .

IDbCommand.ExecuteReader(CommandBehavior)

Esegue l'oggetto CommandTextConnectionsu e compila un IDataReader oggetto usando uno dei CommandBehavior valori .

(Ereditato da DbCommand)
IDbCommand.Parameters

Ottiene l'oggetto IDataParameterCollection.

(Ereditato da DbCommand)
IDbCommand.Transaction

Ottiene o imposta l'oggetto all'interno del quale viene eseguito l'oggetto DbTransactionDbCommand .

(Ereditato da DbCommand)

Si applica a

Vedi anche