如何将参数添加到以下存储过程调用?

问题描述:

如何将参数添加到以下存储过程调用?如何将参数添加到以下存储过程调用?

using (var conn = new SqlConnection(connectionString)) 
using (var command = new SqlCommand("ProcedureName", conn) { 
          CommandType = CommandType.StoredProcedure }) { 
    conn.Open(); 
    command.ExecuteNonQuery(); 
    conn.Close(); 
} 
+2

你已经探索command.Parameters复制? – 2012-01-30 16:24:15

+2

既然你有'use'块,你不需要明确地调用'conn.Close();'。 – Yuck 2012-01-30 16:27:46

+0

帮你一个忙,直接停止使用ado.net,如果你不能使用C#4特性,你可以使用Dapper,Massive,Petapoco等 – BlackTigerX 2012-01-31 00:29:08

可以使用command.Parameters.AddWithValue( “@号”,TextBox1.Text)

编码愉快!

像这样:

// this would work for a varchar or nvarchar parameter 
command.Parameters.AddWithValue("@yourParameter", "someValue"); 
// this would work for an integer parameter 
command.Parameters.AddWithValue("@someInt", 1234); 

显然你需要的任何代码您尝试调用command.ExecuteNonQuery();之前添加参数Parameters收集

我的事情你需要更具体。

使用command.Parameters.AddWithValue时出现什么问题?

这可能是一个解决方案:
该参数应该是存储过程(“yourParameter”)中参数的确切名称。

using (var conn = new SqlConnection(connectionString))
{
var command = new SqlCommand("ProcedureName", conn){CommandType = CommandType.StoredProcedure };
command.Parameters.AddWithValue("@yourParameter", "someValue");
conn.Open();
command.ExecuteNonQuery();
conn.Close();
}

command.Parameters.Add(
     new SqlParameter("@customerId", custumerId)); 

您可以使用SqlCommand.Parameters Property

command.Parameters.Add("@SomeParmeter", SqlDbType.Int); //SqlDbType is enum 

有关详情,请通过这个链接:http://msdn.microsoft.com/en-us/library/yy6y35y8.aspx

下面的代码是从上面贴的链接

static void GetSalesByCategory(string connectionString,string categoryName) 
{ 
    using (SqlConnection connection = new SqlConnection(connectionString)) 
    { 
     // Create the command and set its properties. 
     SqlCommand command = new SqlCommand(); 
     command.Connection = connection; 

     command.CommandText = "SalesByCategory";  
     command.CommandType = CommandType.StoredProcedure; 

     // Add the input parameter and set its properties. 
     SqlParameter parameter = new SqlParameter(); 
     parameter.ParameterName = "@CategoryName"; 
     parameter.SqlDbType = SqlDbType.NVarChar; 
     parameter.Direction = ParameterDirection.Input; 
     parameter.Value = categoryName; 

     // Add the parameter to the Parameters collection. 
     command.Parameters.Add(parameter); 

     // Open the connection and execute the reader. 
     connection.Open(); 
     SqlDataReader reader = command.ExecuteReader(); 

     if (reader.HasRows) 
     { 
      while (reader.Read()) 
      { 
       Console.WriteLine("{0}: {1:C}", reader[0], reader[1]); 
      } 
     } 
     else 
     { 
      Console.WriteLine("No rows found."); 
     } 
     reader.Close(); 
    } 
}