Assembly: System.Data.dll
Represents a parameter to a SqlCommand and is an intrinsic part of the SqlDataReader class.
The SqlParameter class is used to pass parameters to SQL statements. This is essential for preventing SQL injection attacks and for improving the performance of the application by allowing the database to cache execution plans.
public sealed class SqlParameter : IDbDataParameter, ICloneable
-
SqlParameter()Constructor
Initializes a new instance of the
SqlParameterclass. -
SqlParameter(string parameterName, object value)Constructor
Initializes a new instance of the
SqlParameterclass with the specified parameter name and value. -
SqlParameter(string parameterName, SqlDbType SqlDbType, int size)Constructor
Initializes a new instance of the
SqlParameterclass with the specified parameter name, data type, and size. -
ParameterNameProperty (string)
Gets or sets the name of the parameter.
-
SqlDbTypeProperty (SqlDbType)
Gets or sets the SqlDbType of the parameter.
-
ValueProperty (object)
Gets or sets the value of the parameter.
-
DirectionProperty (ParameterDirection)
Gets or sets a value that indicates whether the parameter is an input, output, input/output, or a return value parameter.
-
SizeProperty (int)
Gets or sets the maximum size, in bytes, of the data in the column. The data type of the column determines the actual data type of the parameter.
using System;
using System.Data;
using System.Data.SqlClient;
public class Example
{
public static void Main(string[] args)
{
string connectionString = "Your_Connection_String_Here";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// Create a SqlCommand object
string query = "INSERT INTO Products (ProductName, UnitPrice) VALUES (@Name, @Price)";
using (SqlCommand command = new SqlCommand(query, connection))
{
// Create and configure the parameters
SqlParameter nameParam = new SqlParameter("@Name", SqlDbType.NVarChar, 50);
nameParam.Value = "New Gadget";
SqlParameter priceParam = new SqlParameter("@Price", SqlDbType.Money);
priceParam.Value = 19.99;
// Add the parameters to the command
command.Parameters.Add(nameParam);
command.Parameters.Add(priceParam);
// Execute the command
int rowsAffected = command.ExecuteNonQuery();
Console.WriteLine($"{rowsAffected} row(s) inserted.");
}
}
}
}
The name of the product to be inserted.
The unit price of the product.
When you add a SqlParameter object to the Parameters collection of a SqlCommand, the ADO.NET provider automatically determines the parameter's size if the SqlDbType is set to a variable-length type. You do not need to specify the Size property for these types.
If the Value property is null, the provider sends DBNull.Value to the server. This is different from not setting the parameter's value.