Overview

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.

Syntax
public sealed class SqlParameter : IDbDataParameter, ICloneable
Members
Example
Creating and using a SqlParameter
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."); } } } }
@Name (NVarChar, 50)

The name of the product to be inserted.

@Price (Money)

The unit price of the product.

Remarks

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.

See Also