There are many ways to use SqlParameter in C#. The following will introduce some common usages and provide specific code examples.
Declare a SqlParameter variable:
SqlParameter parameter = new SqlParameter();
Set the name and value of SqlParameter:
parameter.ParameterName = "@ParameterName"; parameter.Value = value;
Set the data type of SqlParameter:
parameter.SqlDbType = SqlDbType.Int;
Set the direction of SqlParameter (input, output, input and output):
parameter.Direction = ParameterDirection.Input;
Set the size of SqlParameter/ Length:
parameter.Size = 50;
Add SqlParameter to the parameter collection of SqlCommand:
command.Parameters.Add(parameter);
Get SqlParameter through the indexer of SqlParameterCollection:
SqlParameter parameter = command.Parameters[index];
Use SqlParameter to perform SQL queries:
using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); string sql = "SELECT * FROM MyTable WHERE Column = @Column"; using (SqlCommand command = new SqlCommand(sql, connection)) { SqlParameter parameter = new SqlParameter("@Column", value); command.Parameters.Add(parameter); SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { // 处理查询结果 } } }
Use SqlParameter to perform insert, update and delete operations:
using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); string sql = "INSERT INTO MyTable (Column1, Column2) VALUES (@Column1, @Column2)"; using (SqlCommand command = new SqlCommand(sql, connection)) { SqlParameter parameter1 = new SqlParameter("@Column1", value1); command.Parameters.Add(parameter1); SqlParameter parameter2 = new SqlParameter("@Column2", value2); command.Parameters.Add(parameter2); int rowsAffected = command.ExecuteNonQuery(); } }
In short, by using SqlParameter, we can perform safe and effective database operations by adding parameters to the SqlCommand object. Whether it is query or insert, update and delete operations, using SqlParameter can help us build more secure and reliable database code.
The above is the detailed content of A guide to using SqlParameter in C#. For more information, please follow other related articles on the PHP Chinese website!