Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Este artigo foi traduzido por mquina. Para visualizar o arquivo em ingls, marque a caixa de seleo Ingls. Voc tambm pode exibir o texto Em
ingls em uma janela pop-up, movendo o ponteiro do mouse sobre o texto.
Classe SqlCommand
.NET Framework (current version)
Representa uma instruo Transact-SQL ou procedimento armazenado para execuo em um banco de dados SQL Server. Essa classe no pode ser
herdada.
Namespace: System.Data.SqlClient
Assembly: System.Data (em System.Data.dll)
Hierarquia de Herana
System.Object
System.MarshalByRefObject
System.ComponentModel.Component
System.Data.Common.DbCommand
System.Data.SqlClient.SqlCommand
Sintaxe
VB
Construtores
Nome Descrio
Propriedades
1 de 12 21/07/2017 11:31
Classe SqlCommand (System.Data.SqlClient) https://msdn.microsoft.com/pt-br/library/system.data.sqlclient.sqlcom...
Nome Descrio
CommandText Obtm ou define a instruo Transact-SQL, nome da tabela ou procedimento armazenado a ser
executado na fonte de dados.(Substitui o DbCommand.CommandText.)
CommandTimeout Obtm ou define o tempo de espera antes do trmino da tentativa de executar um comando e
antes de gerar um erro.(Substitui o DbCommand.CommandTimeout.)
CommandType Obtm ou define um valor que indica como a propriedade CommandText deve ser interpretada.
(Substitui o DbCommand.CommandType.)
DesignTimeVisible Obtm ou define um valor que indica se o objeto de comando deve estar visvel em um
controle do Windows Form Designer.(Substitui o DbCommand.DesignTimeVisible.)
Notification Obtm ou define um valor que especifica o objeto SqlNotificationRequest associado a este
comando.
NotificationAutoEnlist Obtm ou define um valor que indica se o aplicativo deve receber notificaes de consulta
automaticamente de um objeto SqlDependency comum.
UpdatedRowSource Obtm ou define como os resultados do comando so aplicados a DataRow quando usado
pelo mtodo Update de DbDataAdapter.(Substitui o DbCommand.UpdatedRowSource.)
Mtodos
Nome Descrio
2 de 12 21/07/2017 11:31
Classe SqlCommand (System.Data.SqlClient) https://msdn.microsoft.com/pt-br/library/system.data.sqlclient.sqlcom...
de retorno de chamada.
Clone() Cria um novo objeto SqlCommand que uma cpia da instncia atual.
3 de 12 21/07/2017 11:31
Classe SqlCommand (System.Data.SqlClient) https://msdn.microsoft.com/pt-br/library/system.data.sqlclient.sqlcom...
O token de cancelamento pode ser usado para solicitar que a operao seja
abandonada antes de expirar o tempo limite do comando. As excees
sero relatadas por meio do objeto de tarefa.
O token de cancelamento pode ser usado para solicitar que a operao seja
abandonada antes de expirar o tempo limite do comando. As excees
sero relatadas por meio do objeto de tarefa.
O token de cancelamento pode ser usado para solicitar que a operao seja
abandonada antes de expirar o tempo limite do comando. As excees
sero relatadas por meio do objeto de tarefa.(Substitui o
DbCommand.ExecuteScalarAsync(CancellationToken).)
O token de cancelamento pode ser usado para solicitar que a operao ser
abandonado antes de expira o tempo limite do comando. Excees sero
informadas por meio do objeto de tarefa retornado.
GetLifetimeService() Recupera o objeto atual de servio de vida til que controla a diretiva de
vida til para esta instncia. (Herdado de MarshalByRefObject.)
Prepare() Cria uma verso preparada do comando em uma instncia do SQL Server.
(Substitui o DbCommand.Prepare().)
4 de 12 21/07/2017 11:31
Classe SqlCommand (System.Data.SqlClient) https://msdn.microsoft.com/pt-br/library/system.data.sqlclient.sqlcom...
Eventos
Nome Descrio
Disposed Ocorre quando o componente disposto por uma chamada para o mtodo Dispose.(Herdado de
Component.)
Nome Descrio
ICloneable.Clone() Cria um novo SqlCommand objeto que uma cpia da instncia atual.
Comentrios
Quando uma instncia de SqlCommand criado, a leitura/gravao propriedades so definidas para seus valores iniciais. Para obter uma lista
desses valores, consulte o SqlCommand construtor.
SqlCommandapresenta os seguintes mtodos para executar comandos em um banco de dados do SQL Server:
Item Descrio
BeginExecuteNonQuery Inicia a execuo assncrona da instruo Transact-SQL ou procedimento armazenado que descrito por esta
SqlCommand, geralmente executando comandos, como insero, excluso, atualizao e instrues SET. Cada
chamada para BeginExecuteNonQuery devem estar combinados com uma chamada para EndExecuteNonQuery
que termina a operao, geralmente em um thread separado.
5 de 12 21/07/2017 11:31
Classe SqlCommand (System.Data.SqlClient) https://msdn.microsoft.com/pt-br/library/system.data.sqlclient.sqlcom...
BeginExecuteReader Inicia a execuo assncrona da instruo Transact-SQL ou procedimento armazenado que descrito por esta
SqlCommand e recupera os resultados de um ou mais conjuntos de servidor. Cada chamada para
BeginExecuteReader devem estar combinados com uma chamada para EndExecuteReader que termina a
operao, geralmente em um thread separado.
BeginExecuteXmlReader Inicia a execuo assncrona da instruo Transact-SQL ou procedimento armazenado que descrito por este
SqlCommand. Cada chamada para BeginExecuteXmlReader devem estar combinados com uma chamada para
EndExecuteXmlReader, que termina a operao, geralmente em um thread separado e retorna um XmlReader
objeto.
ExecuteReader Executa comandos que retornam linhas. Para melhorar o desempenho, ExecuteReader invoca comandos usando o
Transact-SQL sp_executesql procedimento armazenado do sistema. Portanto, ExecuteReader no pode ter o
efeito que voc deseja se usado para executar comandos como instrues Transact-SQL SET.
ExecuteNonQuery Executa comandos como instrues Transact-SQL INSERT, DELETE, UPDATE e conjunto.
ExecuteScalar Recupera um valor nico (por exemplo, um valor agregado) de um banco de dados.
Voc pode redefinir o CommandText propriedade e reutilizao de SqlCommand objeto. No entanto, voc deve fechar o SqlDataReader antes
de executar um comando de novo ou anterior.
Se um SqlException gerado, o mtodo executando um SqlCommand, o SqlConnection permanece aberto quando o nvel de severidade 19 ou
menos. Quando o nvel de severidade 20 ou maior, o servidor normalmente fecha o SqlConnection. No entanto, o usurio pode reabrir a
conexo e continuar.
Observao
Sem nome, tambm chamado de ordinal, parmetros no so suportados pelo provedor de dados .NET Framework para SQL Server.
Exemplos
O exemplo a seguir cria um SqlConnection, um SqlCommande um SqlDataReader. O exemplo l os dados, grav-la no console. Finalmente, o
exemplo fecha o SqlDataReader e, em seguida, o SqlConnection conforme ela sai do Using blocos de cdigo.
VB
O exemplo a seguir mostra como criar e executar diferentes tipos de objetos SqlCommand.
Primeiro voc deve criar o banco de dados de exemplo, executando o script a seguir:
6 de 12 21/07/2017 11:31
Classe SqlCommand (System.Data.SqlClient) https://msdn.microsoft.com/pt-br/library/system.data.sqlclient.sqlcom...
USE [master]
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,
7 de 12 21/07/2017 11:31
Classe SqlCommand (System.Data.SqlClient) https://msdn.microsoft.com/pt-br/library/system.data.sqlclient.sqlcom...
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
8 de 12 21/07/2017 11:31
Classe SqlCommand (System.Data.SqlClient) https://msdn.microsoft.com/pt-br/library/system.data.sqlclient.sqlcom...
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].[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
9 de 12 21/07/2017 11:31
Classe SqlCommand (System.Data.SqlClient) https://msdn.microsoft.com/pt-br/library/system.data.sqlclient.sqlcom...
using System;
using System.Data;
using System.Data.SqlClient;
using System.Threading.Tasks;
class Program {
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.
10 de 12 21/07/2017 11:31
Classe SqlCommand (System.Data.SqlClient) https://msdn.microsoft.com/pt-br/library/system.data.sqlclient.sqlcom...
conn.Open();
// When using CommandBehavior.CloseConnection, the connection will be closed when the
// IDataReader is closed.
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return reader;
}
}
}
CountCourses(connectionString, 2012);
Console.WriteLine();
Console.WriteLine("Add the credits when the credits of course is lower than 4.");
AddCredits(connectionString, 4);
Console.WriteLine();
// 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;
11 de 12 21/07/2017 11:31
Classe SqlCommand (System.Data.SqlClient) https://msdn.microsoft.com/pt-br/library/system.data.sqlclient.sqlcom...
// 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";
Console.WriteLine("{0} row{1} {2} updated.", rows, rows > 1 ? "s" : null, rows > 1 ? "are" : "is");
}
}
Informaes de Verso
.NET Framework
Disponvel desde 1.1
Acesso thread-safe
Quaisquer membros estticos pblicos ( Compartilhado no Visual Basic) desse tipo so thread-safe. No h garantia de que qualquer membro
de instncia seja thread-safe.
Confira Tambm
Namespace System.Data.SqlClient
Recuperando e modificando dados no ADO.NET
SQL Server e ADO.NET
ADO.NET Managed Providers and DataSet Developer Center
Retornar ao incio
2017 Microsoft
12 de 12 21/07/2017 11:31