2012-01-30 74 views
0

如何將參數添加到以下存儲過程調用?如何將參數添加到以下存儲過程調用?

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

回答

1

可以使用command.Parameters.AddWithValue( 「@號」,TextBox1.Text)

編碼愉快!

2

像這樣:

// 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收集

1

我的事情你需要更具體。

使用command.Parameters.AddWithValue時出現什麼問題?

1

這可能是一個解決方案:
該參數應該是存儲過程(「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();
}

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

有關詳情,請通過這個鏈接: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(); 
    } 
} 
相關問題