SqlParameter Classe
Definição
Representa um parâmetro para um SqlCommand e, opcionalmente, o mapeamento para colunas DataSet.Represents a parameter to a SqlCommand and optionally its mapping to DataSet columns. Essa classe não pode ser herdada.This class cannot be inherited. Para obter mais informações sobre parâmetros, consulte Configurando parâmetros e tipos de dados de parâmetro.For more information on parameters, see Configuring Parameters and Parameter Data Types.
public ref class SqlParameter sealed : System::Data::Common::DbParameter, ICloneable
public ref class SqlParameter sealed : System::Data::Common::DbParameter
public ref class SqlParameter sealed : MarshalByRefObject, ICloneable, System::Data::IDbDataParameter
public sealed class SqlParameter : System.Data.Common.DbParameter, ICloneable
[System.ComponentModel.TypeConverter(typeof(System.Data.SqlClient.SqlParameter/SqlParameterConverter))]
public sealed class SqlParameter : System.Data.Common.DbParameter, ICloneable
public sealed class SqlParameter : System.Data.Common.DbParameter
[System.ComponentModel.TypeConverter(typeof(System.Data.SqlClient.SqlParameterConverter))]
public sealed class SqlParameter : MarshalByRefObject, ICloneable, System.Data.IDbDataParameter
[System.ComponentModel.TypeConverter("System.Data.SqlClient.SqlParameter+SqlParameterConverter, System.Data, Version=2.0.5.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public sealed class SqlParameter : System.Data.Common.DbParameter, ICloneable
[System.ComponentModel.TypeConverter("System.Data.SqlClient.SqlParameter+SqlParameterConverter, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public sealed class SqlParameter : System.Data.Common.DbParameter, ICloneable
type SqlParameter = class
inherit DbParameter
interface ICloneable
[<System.ComponentModel.TypeConverter(typeof(System.Data.SqlClient.SqlParameter/SqlParameterConverter))>]
type SqlParameter = class
inherit DbParameter
interface ICloneable
type SqlParameter = class
inherit DbParameter
[<System.ComponentModel.TypeConverter(typeof(System.Data.SqlClient.SqlParameterConverter))>]
type SqlParameter = class
inherit MarshalByRefObject
interface IDbDataParameter
interface IDataParameter
interface ICloneable
[<System.ComponentModel.TypeConverter(typeof(System.Data.SqlClient.SqlParameter/SqlParameterConverter))>]
type SqlParameter = class
inherit DbParameter
interface IDbDataParameter
interface IDataParameter
interface ICloneable
[<System.ComponentModel.TypeConverter("System.Data.SqlClient.SqlParameter+SqlParameterConverter, System.Data, Version=2.0.5.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")>]
type SqlParameter = class
inherit DbParameter
interface IDbDataParameter
interface IDataParameter
interface ICloneable
[<System.ComponentModel.TypeConverter("System.Data.SqlClient.SqlParameter+SqlParameterConverter, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")>]
type SqlParameter = class
inherit DbParameter
interface IDbDataParameter
interface IDataParameter
interface ICloneable
Public NotInheritable Class SqlParameter
Inherits DbParameter
Implements ICloneable
Public NotInheritable Class SqlParameter
Inherits DbParameter
Public NotInheritable Class SqlParameter
Inherits MarshalByRefObject
Implements ICloneable, IDbDataParameter
- Herança
- Herança
- Herança
- Atributos
- Implementações
Exemplos
O exemplo a seguir cria várias instâncias do SqlParameter por meio da SqlParameterCollection coleção dentro do SqlDataAdapter .The following example creates multiple instances of SqlParameter through the SqlParameterCollection collection within the SqlDataAdapter. Esses parâmetros são usados para selecionar dados da fonte de dados e colocar os dados no DataSet .These parameters are used to select data from the data source and put the data in the DataSet. Este exemplo supõe que um DataSet e um SqlDataAdapter já tenham sido criados usando o esquema, os comandos e a conexão apropriados.This example assumes that a DataSet and a SqlDataAdapter have already been created by using the appropriate schema, commands, and connection. Para obter mais informações e exemplos adicionais sobre como usar parâmetros, consulte recuperando e modificando dados em ADO.net e configurando parâmetros e tipos de dados de parâmetro.For more information and additional examples on using parameters, see Retrieving and Modifying Data in ADO.NET and Configuring Parameters and Parameter Data Types.
public void AddSqlParameters()
{
// ...
// create categoriesDataSet and categoriesAdapter
// ...
categoriesAdapter.SelectCommand.Parameters.Add(
"@CategoryName", SqlDbType.VarChar, 80).Value = "toasters";
categoriesAdapter.SelectCommand.Parameters.Add(
"@SerialNum", SqlDbType.Int).Value = 239;
categoriesAdapter.Fill(categoriesDataSet);
}
Public Sub AddSqlParameters()
' ...
' create categoriesDataSet and categoriesAdapter
' ...
categoriesAdapter.SelectCommand.Parameters.Add( _
"@CategoryName", SqlDbType.VarChar, 80).Value = "toasters"
categoriesAdapter.SelectCommand.Parameters.Add( _
"@SerialNum", SqlDbType.Int).Value = 239
categoriesAdapter.Fill(categoriesDataSet)
End Sub
Comentários
Os nomes de parâmetro não diferenciam maiúsculas de minúsculas.Parameter names are not case sensitive.
Observação
Sem nome, também chamadas de parâmetros ordinais, não são suportados pelo Provedor de Dados .NET Framework para SQL Server.Nameless, also called ordinal, parameters are not supported by the .NET Framework Data Provider for SQL Server.
Para obter mais informações, juntamente com o código de exemplo adicional que demonstra como usar parâmetros, consulte comandos e parâmetros.For more information, along with additional sample code demonstrating how to use parameters, see Commands and Parameters.
Construtores
| SqlParameter() |
Inicializa uma nova instância da classe SqlParameter.Initializes a new instance of the SqlParameter class. |
| SqlParameter(String, Object) |
Inicializa uma nova instância da classe SqlParameter que usa o nome do parâmetro e um valor do novo SqlParameter.Initializes a new instance of the SqlParameter class that uses the parameter name and a value of the new SqlParameter. |
| SqlParameter(String, SqlDbType) |
Inicializa uma nova instância da classe SqlParameter que usa o nome do parâmetro e o tipo de dados.Initializes a new instance of the SqlParameter class that uses the parameter name and the data type. |
| SqlParameter(String, SqlDbType, Int32) |
Inicializa uma nova instância da classe SqlParameter que usa o nome do parâmetro, o SqlDbType e o tamanho.Initializes a new instance of the SqlParameter class that uses the parameter name, the SqlDbType, and the size. |
| SqlParameter(String, SqlDbType, Int32, ParameterDirection, Boolean, Byte, Byte, String, DataRowVersion, Object) |
Inicializa uma nova instância da classe SqlParameter que usa o nome do parâmetro, o tipo do parâmetro, o tamanho do parâmetro, um ParameterDirection, a precisão do parâmetro, a escala do parâmetro, a coluna de origem, um DataRowVersion a ser usado e o valor do parâmetro.Initializes a new instance of the SqlParameter class that uses the parameter name, the type of the parameter, the size of the parameter, a ParameterDirection, the precision of the parameter, the scale of the parameter, the source column, a DataRowVersion to use, and the value of the parameter. |
| SqlParameter(String, SqlDbType, Int32, ParameterDirection, Byte, Byte, String, DataRowVersion, Boolean, Object, String, String, String) |
Inicializa uma nova instância da classe SqlParameter que usa o nome do parâmetro, o tipo do parâmetro, o tamanho do parâmetro, a direção, a precisão, a escala, o nome da coluna de origem, um dos valores DataRowVersion, um booliano para o mapeamento da coluna de origem, o valor do |
| SqlParameter(String, SqlDbType, Int32, String) |
Inicializa uma nova instância da classe SqlParameter que usa o nome do parâmetro, o SqlDbType, o tamanho e o nome da coluna de origem.Initializes a new instance of the SqlParameter class that uses the parameter name, the SqlDbType, the size, and the source column name. |
Propriedades
| CompareInfo |
Obtém ou define o objeto CompareInfo que define como as comparações de cadeia de caracteres devem ser realizadas neste parâmetro.Gets or sets the CompareInfo object that defines how string comparisons should be performed for this parameter. |
| DbType |
Obtém ou define o SqlDbType do parâmetro.Gets or sets the SqlDbType of the parameter. |
| Direction |
Obtém ou define um valor que indica se o parâmetro é apenas de entrada, saída, bidirecional ou um parâmetro de valor retornado do procedimento armazenado.Gets or sets a value that indicates whether the parameter is input-only, output-only, bidirectional, or a stored procedure return value parameter. |
| ForceColumnEncryption |
Impõe a criptografia de um parâmetro ao usar Always Encrypted.Enforces encryption of a parameter when using Always Encrypted. Se o SQL Server informar o driver que o parâmetro não precisa ser criptografado, a consulta que estiver o parâmetro falhará.If SQL Server informs the driver that the parameter does not need to be encrypted, the query using the parameter will fail. Essa propriedade fornece proteção adicional contra ataques de segurança que envolvem um SQL Server comprometido fornecendo metadados de criptografia incorretos ao cliente, o que pode levar à divulgação de dados.This property provides additional protection against security attacks that involve a compromised SQL Server providing incorrect encryption metadata to the client, which may lead to data disclosure. |
| IsNullable |
Obtém ou define um valor que indica se o parâmetro aceita valores nulos.Gets or sets a value that indicates whether the parameter accepts null values. IsNullable não é usado para validar o valor do parâmetro e não impedirá o envio nem o recebimento de um valor nulo ao executar um comando.IsNullable is not used to validate the parameter's value and will not prevent sending or receiving a null value when executing a command. |
| LocaleId |
Obtém ou define o identificador de localidade que determina as convenções e o idioma para uma região específica.Gets or sets the locale identifier that determines conventions and language for a particular region. |
| Offset |
Obtém ou define o deslocamento para a propriedade Value.Gets or sets the offset to the Value property. |
| ParameterName |
Obtém ou define o nome de SqlParameter.Gets or sets the name of the SqlParameter. |
| Precision |
Obtém ou define o número máximo de dígitos usados para representar a propriedade Value.Gets or sets the maximum number of digits used to represent the Value property. |
| Scale |
Obtém ou define o número de casas decimais para as quais o Value é resolvido.Gets or sets the number of decimal places to which Value is resolved. |
| Size |
Obtém ou define o tamanho máximo, em bytes, dos dados da coluna.Gets or sets the maximum size, in bytes, of the data within the column. |
| SourceColumn |
Obtém ou define o nome da coluna de origem mapeada para o DataSet e usada para carregar ou retornar o ValueGets or sets the name of the source column mapped to the DataSet and used for loading or returning the Value |
| SourceColumnNullMapping |
Obtém ou define um valor que indica se a coluna de origem permite valor nulo.Gets or sets a value which indicates whether the source column is nullable. Isso permite que SqlCommandBuilder gere corretamente instruções Update para colunas que permitem valor nulo.This allows SqlCommandBuilder to correctly generate Update statements for nullable columns. |
| SourceVersion |
Obtém ou define o DataRowVersion a ser usado ao carregar ValueGets or sets the DataRowVersion to use when you load Value |
| SourceVersion |
Obtém ou define o DataRowVersion a ser usado ao carregar Value.Gets or sets the DataRowVersion to use when you load Value. (Herdado de DbParameter) |
| SqlDbType |
Obtém ou define o SqlDbType do parâmetro.Gets or sets the SqlDbType of the parameter. |
| SqlValue |
Obtém ou define o valor do parâmetro como um tipo SQL.Gets or sets the value of the parameter as an SQL type. |
| TypeName |
Obtém ou define o nome do tipo para um parâmetro com valor de tabela.Gets or sets the type name for a table-valued parameter. |
| UdtTypeName |
Obtém ou define um |
| Value |
Obtém ou define o valor do parâmetro.Gets or sets the value of the parameter. |
| XmlSchemaCollectionDatabase |
Obtém o nome do banco de dados em que a coleção de esquemas dessa instância XML está localizada.Gets the name of the database where the schema collection for this XML instance is located. |
| XmlSchemaCollectionName |
Obtém o nome da coleção de esquemas desta instância XML.Gets the name of the schema collection for this XML instance. |
| XmlSchemaCollectionOwningSchema |
O esquema relacional proprietário em que a coleção de esquemas dessa instância XML está localizada.The owning relational schema where the schema collection for this XML instance is located. |
Métodos
| CreateObjRef(Type) |
Cria um objeto que contém todas as informações relevantes necessárias para gerar um proxy usado para se comunicar com um objeto remoto.Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Herdado de MarshalByRefObject) |
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object. (Herdado de Object) |
| GetHashCode() |
Serve como a função de hash padrão.Serves as the default hash function. (Herdado de Object) |
| GetLifetimeService() |
Obsoleto.
Recupera o objeto de serviço de tempo de vida atual que controla a política de ciclo de vida para esta instância.Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Herdado de MarshalByRefObject) |
| GetType() |
Obtém o Type da instância atual.Gets the Type of the current instance. (Herdado de Object) |
| InitializeLifetimeService() |
Obsoleto.
Obtém um objeto de serviço de tempo de vida para controlar a política de tempo de vida para essa instância.Obtains a lifetime service object to control the lifetime policy for this instance. (Herdado de MarshalByRefObject) |
| MemberwiseClone() |
Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object. (Herdado de Object) |
| MemberwiseClone(Boolean) |
Cria uma cópia superficial do objeto MarshalByRefObject atual.Creates a shallow copy of the current MarshalByRefObject object. (Herdado de MarshalByRefObject) |
| ResetDbType() |
Redefine o tipo associado a este SqlParameter.Resets the type associated with this SqlParameter. |
| ResetSqlDbType() |
Redefine o tipo associado a este SqlParameter.Resets the type associated with this SqlParameter. |
| ToString() |
Obtém uma cadeia de caracteres que contém o ParameterName.Gets a string that contains the ParameterName. |
Implantações explícitas de interface
| ICloneable.Clone() |
Para obter uma descrição desse membro, confira Clone().For a description of this member, see Clone(). |
| IDataParameter.SourceVersion |
Obtém ou define o DataRowVersion a ser usado ao carregar Value.Gets or sets the DataRowVersion to use when loading Value. (Herdado de DbParameter) |
| IDbDataParameter.Precision |
Indica a precisão de parâmetros numéricos.Indicates the precision of numeric parameters. (Herdado de DbParameter) |
| IDbDataParameter.Scale |
Para obter uma descrição desse membro, confira Scale.For a description of this member, see Scale. (Herdado de DbParameter) |