SqlCommand SqlCommand SqlCommand SqlCommand Class

定义

表示要对 SQL Server 数据库执行的一个 Transact-SQL 语句或存储过程。Represents a Transact-SQL statement or stored procedure to execute against a SQL Server database. 此类不能被继承。This class cannot be inherited.

public ref class SqlCommand sealed : System::Data::Common::DbCommand, ICloneable, IDisposable
public sealed class SqlCommand : System.Data.Common.DbCommand, ICloneable, IDisposable
type SqlCommand = class
    inherit DbCommand
    interface IDbCommand
    interface ICloneable
    interface IDisposable
Public NotInheritable Class SqlCommand
Inherits DbCommand
Implements ICloneable, IDisposable
继承
实现

示例

下面的示例创建一个SqlConnection、一个SqlCommand和一个SqlDataReaderThe following example creates a SqlConnection, a SqlCommand, and a SqlDataReader. 该示例将读取数据,并将数据写入控制台。The example reads through the data, writing it to the console. 最后,此示例将关闭SqlDataReaderSqlConnection然后Using关闭代码块。Finally, the example closes the SqlDataReader and then the SqlConnection as it exits the Using code blocks.

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

下面的示例演示如何创建和执行不同类型的 SqlCommand 对象。The following sample shows how to create and execute different types of SqlCommand objects.

首先,必须通过执行以下脚本来创建示例数据库:First you must create the sample database, by executing the following script:

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  

接下来,编译并执行以下操作:Next, compile and execute the following:

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");  
   }  
}  

注解

创建的SqlCommand实例时,读/写属性将设置为其初始值。When an instance of SqlCommand is created, the read/write properties are set to their initial values. 有关这些值的列表,请参见SqlCommand构造函数。For a list of these values, see the SqlCommand constructor.

SqlCommand使用以下方法在 SQL Server 数据库中执行命令:SqlCommand features the following methods for executing commands at a SQL Server database:

Item 说明Description
BeginExecuteNonQuery 启动此SqlCommand描述的 transact-sql 语句或存储过程的异步执行,通常执行 INSERT、DELETE、UPDATE 和 SET 语句等命令。Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand, generally executing commands such as INSERT, DELETE, UPDATE, and SET statements. BeginExecuteNonQuery的每个调用都必须与完成操作EndExecuteNonQuery的调用配对,通常在单独的线程上完成。Each call to BeginExecuteNonQuery must be paired with a call to EndExecuteNonQuery which finishes the operation, typically on a separate thread.
BeginExecuteReader 启动此SqlCommand描述的 transact-sql 语句或存储过程的异步执行,并从服务器中检索一个或多个结果集。Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand and retrieves one or more results sets from the server. BeginExecuteReader的每个调用都必须与完成操作EndExecuteReader的调用配对,通常在单独的线程上完成。Each call to BeginExecuteReader must be paired with a call to EndExecuteReader which finishes the operation, typically on a separate thread.
BeginExecuteXmlReader 启动此 SqlCommand 描述的 Transact-SQL 语句或存储过程的异步执行。Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand. BeginExecuteXmlReader的每个调用都必须与对的EndExecuteXmlReader调用配对,后者通常在单独的线程上完成操作,并返回XmlReader一个对象。Each call to BeginExecuteXmlReader must be paired with a call to EndExecuteXmlReader, which finishes the operation, typically on a separate thread, and returns an XmlReader object.
ExecuteReader 执行返回行的命令。Executes commands that return rows. 为了提高性能, ExecuteReader请使用 transact-sql sp_executesql系统存储过程调用命令。For increased performance, ExecuteReader invokes commands using the Transact-SQL sp_executesql system stored procedure. 因此, ExecuteReader如果用于执行 transact-sql SET 语句之类的命令,则可能不会产生所需的效果。Therefore, ExecuteReader might not have the effect that you want if used to execute commands such as Transact-SQL SET statements.
ExecuteNonQuery 执行 Transact-sql INSERT、DELETE、UPDATE 和 SET 语句等命令。Executes commands such as Transact-SQL INSERT, DELETE, UPDATE, and SET statements.
ExecuteScalar 从数据库中检索单个值(例如聚合值)。Retrieves a single value (for example, an aggregate value) from a database.
ExecuteXmlReader CommandText 发送到 Connection,并生成一个 XmlReader 对象。Sends the CommandText to the Connection and builds an XmlReader object.

可以重置CommandText属性并重新使用该SqlCommand对象。You can reset the CommandText property and reuse the SqlCommand object. 但是,必须SqlDataReader先关闭,然后才能执行新的或前一个命令。However, you must close the SqlDataReader before you can execute a new or previous command.

如果由执行的SqlCommand方法生成,则当严重性级别SqlConnection为19或更低时,将保持打开状态。 SqlExceptionIf a SqlException is generated by the method executing a SqlCommand, the SqlConnection remains open when the severity level is 19 or less. 当严重性级别为20或更大时,服务器通常会关闭SqlConnectionWhen the severity level is 20 or greater, the server ordinarily closes the SqlConnection. 但是,用户可以重新打开连接并继续操作。However, the user can reopen the connection and continue.

备注

无名称(也称为序号) .NET Framework 数据提供程序不支持 SQL Server 的参数。Nameless, also called ordinal, parameters are not supported by the .NET Framework Data Provider for SQL Server.

构造函数

SqlCommand() SqlCommand() SqlCommand() SqlCommand()

初始化 SqlCommand 类的新实例。Initializes a new instance of the SqlCommand class.

SqlCommand(String) SqlCommand(String) SqlCommand(String) SqlCommand(String)

使用查询的文本初始化 SqlCommand 类的新实例。Initializes a new instance of the SqlCommand class with the text of the query.

SqlCommand(String, SqlConnection) SqlCommand(String, SqlConnection) SqlCommand(String, SqlConnection) SqlCommand(String, SqlConnection)

使用查询的文本和 SqlConnection 初始化 SqlCommand 类的新实例。Initializes a new instance of the SqlCommand class with the text of the query and a SqlConnection.

SqlCommand(String, SqlConnection, SqlTransaction) SqlCommand(String, SqlConnection, SqlTransaction) SqlCommand(String, SqlConnection, SqlTransaction) SqlCommand(String, SqlConnection, SqlTransaction)

使用查询文本、SqlConnection 以及 SqlTransaction 初始化 SqlCommand 类的新实例。Initializes a new instance of the SqlCommand class with the text of the query, a SqlConnection, and the SqlTransaction.

SqlCommand(String, SqlConnection, SqlTransaction, SqlCommandColumnEncryptionSetting) SqlCommand(String, SqlConnection, SqlTransaction, SqlCommandColumnEncryptionSetting) SqlCommand(String, SqlConnection, SqlTransaction, SqlCommandColumnEncryptionSetting) SqlCommand(String, SqlConnection, SqlTransaction, SqlCommandColumnEncryptionSetting)

使用指定的命令文本、连接、事务和加密设置初始化 SqlCommand 类的新实例。Initializes a new instance of the SqlCommand class with specified command text, connection, transaction, and encryption setting.

属性

CanRaiseEvents CanRaiseEvents CanRaiseEvents CanRaiseEvents

获取一个指示组件是否可以引发事件的值。Gets a value indicating whether the component can raise an event.

(Inherited from Component)
ColumnEncryptionSetting ColumnEncryptionSetting ColumnEncryptionSetting ColumnEncryptionSetting

获取或设置此命令的列加密设置。Gets or sets the column encryption setting for this command.

CommandText CommandText CommandText CommandText

获取或设置要在数据源中执行的 Transact-SQL 语句、表名或存储过程。Gets or sets the Transact-SQL statement, table name or stored procedure to execute at the data source.

CommandTimeout CommandTimeout CommandTimeout CommandTimeout

获取或设置在终止尝试执行命令并生成错误之前的等待时间。Gets or sets the wait time before terminating the attempt to execute a command and generating an error.

CommandType CommandType CommandType CommandType

获取或设置一个值,该值指示解释 CommandText 属性的方式。Gets or sets a value indicating how the CommandText property is to be interpreted.

Connection Connection Connection Connection

获取或设置 SqlCommand 的此实例使用的 SqlConnectionGets or sets the SqlConnection used by this instance of the SqlCommand.

Container Container Container Container

获取 IContainer,它包含 ComponentGets the IContainer that contains the Component.

(Inherited from Component)
DesignMode DesignMode DesignMode DesignMode

获取一个值,用以指示 Component 当前是否处于设计模式。Gets a value that indicates whether the Component is currently in design mode.

(Inherited from Component)
DesignTimeVisible DesignTimeVisible DesignTimeVisible DesignTimeVisible

获取或设置一个值,该值指示命令对象是否应在 Windows 窗体设计器控件中可见。Gets or sets a value indicating whether the command object should be visible in a Windows Form Designer control.

Events Events Events Events

获取附加到此 Component 的事件处理程序的列表。Gets the list of event handlers that are attached to this Component.

(Inherited from Component)
Notification Notification Notification Notification

获取或设置一个指定绑定到此命令的 SqlNotificationRequest 对象的值。Gets or sets a value that specifies the SqlNotificationRequest object bound to this command.

NotificationAutoEnlist NotificationAutoEnlist NotificationAutoEnlist NotificationAutoEnlist

获取或设置一个值,该值指示应用程序是否应自动接收来自通用 SqlDependency 对象的查询通知。Gets or sets a value indicating whether the application should automatically receive query notifications from a common SqlDependency object.

Parameters Parameters Parameters Parameters

获取 SqlParameterCollectionGets the SqlParameterCollection.

Site Site Site Site

获取或设置 ComponentISiteGets or sets the ISite of the Component.

(Inherited from Component)
Transaction Transaction Transaction Transaction

获取或设置要在其中执行 SqlTransactionSqlCommandGets or sets the SqlTransaction within which the SqlCommand executes.

UpdatedRowSource UpdatedRowSource UpdatedRowSource UpdatedRowSource

获取或设置命令结果在由 DbDataAdapter 的 Update 方法使用时应用于 DataRow 的方式。Gets or sets how command results are applied to the DataRow when used by the Update method of the DbDataAdapter.

方法

BeginExecuteNonQuery() BeginExecuteNonQuery() BeginExecuteNonQuery() BeginExecuteNonQuery()

启动此 SqlCommand 描述的 Transact-SQL 语句或存储过程的异步执行。Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand.

BeginExecuteNonQuery(AsyncCallback, Object) BeginExecuteNonQuery(AsyncCallback, Object) BeginExecuteNonQuery(AsyncCallback, Object) BeginExecuteNonQuery(AsyncCallback, Object)

在给定回调过程和状态信息的情况下,启动此 SqlCommand 描述的 Transact-SQL 语句或存储过程的异步执行。Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand, given a callback procedure and state information.

BeginExecuteReader() BeginExecuteReader() BeginExecuteReader() BeginExecuteReader()

启动此 SqlCommand 描述的 Transact-SQL 语句或存储过程的异步执行,并从服务器中检索一个或多个结果集。Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand, and retrieves one or more result sets from the server.

BeginExecuteReader(AsyncCallback, Object) BeginExecuteReader(AsyncCallback, Object) BeginExecuteReader(AsyncCallback, Object) BeginExecuteReader(AsyncCallback, Object)

在给定回调过程和状态信息的情况下,启动此 SqlCommand 描述的 Transact-SQL 语句或存储过程的异步执行,并从服务器中检索一个或多个结果集。Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand and retrieves one or more result sets from the server, given a callback procedure and state information.

BeginExecuteReader(AsyncCallback, Object, CommandBehavior) BeginExecuteReader(AsyncCallback, Object, CommandBehavior) BeginExecuteReader(AsyncCallback, Object, CommandBehavior) BeginExecuteReader(AsyncCallback, Object, CommandBehavior)

在给定回调过程和状态信息的情况下,通过使用 CommandBehavior 值之一并从服务器中检索一个或多个结果集,启动由此 SqlCommand 描述的 Transact-SQL 语句或存储过程的异步执行。Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand, using one of the CommandBehavior values, and retrieving one or more result sets from the server, given a callback procedure and state information.

BeginExecuteReader(CommandBehavior) BeginExecuteReader(CommandBehavior) BeginExecuteReader(CommandBehavior) BeginExecuteReader(CommandBehavior)

通过使用 CommandBehavior 值之一,启动此 SqlCommand 描述的 Transact-SQL 语句或存储过程的异步执行。Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand using one of the CommandBehavior values.

BeginExecuteXmlReader() BeginExecuteXmlReader() BeginExecuteXmlReader() BeginExecuteXmlReader()

启动此 SqlCommand 描述的 Transact-SQL 语句或存储过程的异步执行,并将结果作为 XmlReader 对象返回。Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand and returns results as an XmlReader object.

BeginExecuteXmlReader(AsyncCallback, Object) BeginExecuteXmlReader(AsyncCallback, Object) BeginExecuteXmlReader(AsyncCallback, Object) BeginExecuteXmlReader(AsyncCallback, Object)

通过使用回调过程,启动此 SqlCommand 描述的 Transact-SQL 语句或存储过程的异步执行,并将结果作为 XmlReader 对象返回。Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand and returns results as an XmlReader object, using a callback procedure.

Cancel() Cancel() Cancel() Cancel()

尝试取消 SqlCommand 的执行。Tries to cancel the execution of a SqlCommand.

Clone() Clone() Clone() Clone()

创建属于当前实例的副本的新 SqlCommand 对象。Creates a new SqlCommand object that is a copy of the current instance.

CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type)

创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
CreateParameter() CreateParameter() CreateParameter() CreateParameter()

创建 SqlParameter 对象的新实例。Creates a new instance of a SqlParameter object.

Dispose() Dispose() Dispose() Dispose()

释放由 Component 使用的所有资源。Releases all resources used by the Component.

(Inherited from Component)
Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

释放由 Component 占用的非托管资源,还可以另外再释放托管资源。Releases the unmanaged resources used by the Component and optionally releases the managed resources.

(Inherited from Component)
EndExecuteNonQuery(IAsyncResult) EndExecuteNonQuery(IAsyncResult) EndExecuteNonQuery(IAsyncResult) EndExecuteNonQuery(IAsyncResult)

完成 Transact-SQL 语句的异步执行。Finishes asynchronous execution of a Transact-SQL statement.

EndExecuteReader(IAsyncResult) EndExecuteReader(IAsyncResult) EndExecuteReader(IAsyncResult) EndExecuteReader(IAsyncResult)

完成 Transact-SQL 语句的异步执行,从而返回请求的 SqlDataReaderFinishes asynchronous execution of a Transact-SQL statement, returning the requested SqlDataReader.

EndExecuteXmlReader(IAsyncResult) EndExecuteXmlReader(IAsyncResult) EndExecuteXmlReader(IAsyncResult) EndExecuteXmlReader(IAsyncResult)

完成 Transact-SQL 语句的异步执行,从而将请求的数据以 XML 形式返回。Finishes asynchronous execution of a Transact-SQL statement, returning the requested data as XML.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(Inherited from Object)
ExecuteNonQuery() ExecuteNonQuery() ExecuteNonQuery() ExecuteNonQuery()

对连接执行 Transact-SQL 语句并返回受影响的行数。Executes a Transact-SQL statement against the connection and returns the number of rows affected.

ExecuteNonQueryAsync(CancellationToken) ExecuteNonQueryAsync(CancellationToken) ExecuteNonQueryAsync(CancellationToken) ExecuteNonQueryAsync(CancellationToken)

ExecuteNonQuery() 的异步版本,它对连接执行 Transact-SQLTransact-SQL 语句并返回受影响的行数。An asynchronous version of ExecuteNonQuery(), which executes a Transact-SQLTransact-SQL statement against the connection and returns the number of rows affected. 取消标记可用于请求在命令超时超过前放弃操作。The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. 将通过返回的任务对象报告异常。Exceptions will be reported via the returned Task object.

ExecuteReader() ExecuteReader() ExecuteReader() ExecuteReader()

CommandText 发送到 Connection,并生成 SqlDataReaderSends the CommandText to the Connection and builds a SqlDataReader.

ExecuteReader(CommandBehavior) ExecuteReader(CommandBehavior) ExecuteReader(CommandBehavior) ExecuteReader(CommandBehavior)

CommandText 发送到 Connection,并使用 CommandBehavior 值之一生成 SqlDataReaderSends the CommandText to the Connection, and builds a SqlDataReader using one of the CommandBehavior values.

ExecuteReaderAsync() ExecuteReaderAsync() ExecuteReaderAsync() ExecuteReaderAsync()

ExecuteReader() 的异步版本,它可以将 CommandText 发送到 Connection,并生成 SqlDataReaderAn asynchronous version of ExecuteReader(), which sends the CommandText to the Connection and builds a SqlDataReader. 将通过返回的任务对象报告异常。Exceptions will be reported via the returned Task object.

ExecuteReaderAsync(CancellationToken) ExecuteReaderAsync(CancellationToken) ExecuteReaderAsync(CancellationToken) ExecuteReaderAsync(CancellationToken)

ExecuteReader() 的异步版本,它可以将 CommandText 发送到 Connection,并生成 SqlDataReaderAn asynchronous version of ExecuteReader(), which sends the CommandText to the Connection and builds a SqlDataReader.

取消标记可用于请求在命令超时超过前放弃操作。The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. 将通过返回的任务对象报告异常。Exceptions will be reported via the returned Task object.

ExecuteReaderAsync(CommandBehavior) ExecuteReaderAsync(CommandBehavior) ExecuteReaderAsync(CommandBehavior) ExecuteReaderAsync(CommandBehavior)

ExecuteReader(CommandBehavior) 的异步版本,用于将 CommandText 发送到 Connection,并生成一个 SqlDataReaderAn asynchronous version of ExecuteReader(CommandBehavior), which sends the CommandText to the Connection, and builds a SqlDataReader. 将通过返回的任务对象报告异常。Exceptions will be reported via the returned Task object.

ExecuteReaderAsync(CommandBehavior, CancellationToken) ExecuteReaderAsync(CommandBehavior, CancellationToken) ExecuteReaderAsync(CommandBehavior, CancellationToken) ExecuteReaderAsync(CommandBehavior, CancellationToken)

ExecuteReader(CommandBehavior) 的异步版本,它可以将 CommandText 发送到 Connection,并生成 SqlDataReaderAn asynchronous version of ExecuteReader(CommandBehavior), which sends the CommandText to the Connection, and builds a SqlDataReader

取消标记可用于请求在命令超时超过前放弃操作。The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. 将通过返回的任务对象报告异常。Exceptions will be reported via the returned Task object.

ExecuteScalar() ExecuteScalar() ExecuteScalar() ExecuteScalar()

执行查询,并返回由查询返回的结果集中的第一行的第一列。Executes the query, and returns the first column of the first row in the result set returned by the query. 其他列或行将被忽略。Additional columns or rows are ignored.

ExecuteScalarAsync(CancellationToken) ExecuteScalarAsync(CancellationToken) ExecuteScalarAsync(CancellationToken) ExecuteScalarAsync(CancellationToken)

ExecuteScalar() 的异步版本,该版本异步执行查询,并返回由查询返回的结果集中的第一行的第一列。An asynchronous version of ExecuteScalar(), which executes the query asynchronously and returns the first column of the first row in the result set returned by the query. 其他列或行将被忽略。Additional columns or rows are ignored.

取消标记可用于请求在命令超时超过前放弃操作。The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. 将通过返回的任务对象报告异常。Exceptions will be reported via the returned Task object.

ExecuteXmlReader() ExecuteXmlReader() ExecuteXmlReader() ExecuteXmlReader()

CommandText 发送到 Connection,并生成一个 XmlReader 对象。Sends the CommandText to the Connection and builds an XmlReader object.

ExecuteXmlReaderAsync() ExecuteXmlReaderAsync() ExecuteXmlReaderAsync() ExecuteXmlReaderAsync()

ExecuteXmlReader() 的异步版本,可以将 CommandText 发送到 Connection,并生成 XmlReader 对象。An asynchronous version of ExecuteXmlReader(), which sends the CommandText to the Connection and builds an XmlReader object.

将通过返回的任务对象报告异常。Exceptions will be reported via the returned Task object.

ExecuteXmlReaderAsync(CancellationToken) ExecuteXmlReaderAsync(CancellationToken) ExecuteXmlReaderAsync(CancellationToken) ExecuteXmlReaderAsync(CancellationToken)

ExecuteXmlReader() 的异步版本,可以将 CommandText 发送到 Connection,并生成 XmlReader 对象。An asynchronous version of ExecuteXmlReader(), which sends the CommandText to the Connection and builds an XmlReader object.

取消标记可用于请求在命令超时超过前放弃操作。The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. 将通过返回的任务对象报告异常。Exceptions will be reported via the returned Task object.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(Inherited from Object)
GetLifetimeService() GetLifetimeService() GetLifetimeService() GetLifetimeService()

检索控制此实例的生存期策略的当前生存期服务对象。Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetService(Type) GetService(Type) GetService(Type) GetService(Type)

返回一个对象,该对象表示由 Component 或它的 Container 提供的服务。Returns an object that represents a service provided by the Component or by its Container.

(Inherited from Component)
GetType() GetType() GetType() GetType()

获取当前实例的 TypeGets the Type of the current instance.

(Inherited from Object)
InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService()

获取生存期服务对象来控制此实例的生存期策略。Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean)

创建当前 MarshalByRefObject 对象的浅表副本。Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
Prepare() Prepare() Prepare() Prepare()

在 SQL Server 的实例上创建命令的一个准备版本。Creates a prepared version of the command on an instance of SQL Server.

ResetCommandTimeout() ResetCommandTimeout() ResetCommandTimeout() ResetCommandTimeout()

CommandTimeout 属性重置为其默认值。Resets the CommandTimeout property to its default value.

ToString() ToString() ToString() ToString()

返回包含 Component 的名称的 String(如果有)。Returns a String containing the name of the Component, if any. 不应重写此方法。This method should not be overridden.

(Inherited from Component)

事件

Disposed Disposed Disposed Disposed

当通过调用 Dispose() 方法释放组件时发生。Occurs when the component is disposed by a call to the Dispose() method.

(Inherited from Component)
StatementCompleted StatementCompleted StatementCompleted StatementCompleted

当 Transact-SQL 语句执行完成时发生。Occurs when the execution of a Transact-SQL statement completes.

显式界面实现

ICloneable.Clone() ICloneable.Clone() ICloneable.Clone() ICloneable.Clone()

创建属于当前实例的副本的新 SqlCommand 对象。Creates a new SqlCommand object that is a copy of the current instance.

IDbCommand.CreateParameter() IDbCommand.CreateParameter() IDbCommand.CreateParameter() IDbCommand.CreateParameter()

创建 SqlParameter 对象的新实例。Creates a new instance of a SqlParameter object.

IDbCommand.ExecuteReader() IDbCommand.ExecuteReader() IDbCommand.ExecuteReader() IDbCommand.ExecuteReader()

CommandText 发送到 Connection,并生成一个 SqlDataReaderSends the CommandText to the Connection, and builds a SqlDataReader.

IDbCommand.ExecuteReader(CommandBehavior) IDbCommand.ExecuteReader(CommandBehavior) IDbCommand.ExecuteReader(CommandBehavior) IDbCommand.ExecuteReader(CommandBehavior)

CommandText 发送到 Connection,并使用 CommandBehavior 值之一生成 SqlDataReaderSends the CommandText to the Connection, and builds a SqlDataReader using one of the CommandBehavior values.

适用于

另请参阅