2010-06-01 26 views

回答

6

如果您使用的Enterprise Library,這種風格將工作做好你:

using System; 
using System.Collections.Generic; 
using System.Data; 
using System.Data.Common; 
using System.Data.SqlClient; 
using System.Text; 
using Microsoft.Practices.EnterpriseLibrary.Data.Sql; 

// ... 

SqlDatabase db = new SqlDatabase("YourConnectionString"); 
DbCommand cmd = db.GetStoredProcCommand("YourProcName"); 
cmd.Parameters.Add(new SqlParameter("YourParamName", "param value")); 

using (IDataReader dr = db.ExecuteReader(cmd)) 
{ 
    while (dr.Read()) 
    { 
     // do something with the data 
    } 
} 
+1

添加了參考文獻,它工作得很好。 – 2010-06-02 18:07:22

8

處理參數的不是IDataReader,而是IDbCommand(使用CreateParameter方法)。然後,您可以使用ExecuteReader方法獲取該命令的閱讀器。

我把一個簡單的例子:

private static void ExecuteCommand(IDbConnection conn) 
{ 
    using (IDbCommand cmd = conn.CreateCommand()) 
    { 
     cmd.CommandType = CommandType.StoredProcedure; 
     cmd.CommandText = "ProcedureName"; 
     IDataParameter param = cmd.CreateParameter(); 
     param.ParameterName = "@parameterName"; 
     param.Value = "parameter value"; 
     cmd.Parameters.Add(param); 
     using (IDataReader reader = cmd.ExecuteReader()) 
     { 
      while (reader.Read()) 
      { 
       // get data from the reader 
      } 
     } 
    } 
} 
+1

是,並將'IDbCommand'的'CommandType'屬性設置爲'CommandType.StoredProcedure'。 – stakx 2010-06-01 21:36:41

1

一些.NET提供有一個靜態DeriveParameters()方法在命令生成器實現中。如果是這樣,您可以使用它來檢索參數列表,然後填寫值。它提供的「發現」的信息的好辦法:

IDbCommand cmd = conn.CreateCommand(); 

cmd.CommandText = "SomeProcedure"; 
cmd.CommandType = CommandType.StoredProcedure; 

// to avoid hard coded reference to a specific provider type, get a 
// command builder object and use reflection to invoke the derive method 
DbCommandBuilder cb = dbfact.CreateCommandBuilder(); 
MethodInfo mi = cb.GetType().GetMethod("DeriveParameters", 
           BindingFlags.Public | BindingFlags.Static); 
mi.Invoke(null, new object[] { cmd }); 
// show information about each parameter 
foreach (IDataParameter p in cmd.Parameters) 
    Console.WriteLine("{0}, {1}, {2}", p.ParameterName, 
         p.DbType.ToString(), p.Direction.ToString()); 
IDataParameter prm = (IDataParameter)cmd.Parameters["SomeParam"]; 
prm.Value = "xyz"; 
IDataReader rdr = cmd.ExecuteReader(); 
0

下面的示例爲我工作(傳遞參數名存實亡我只試過這種字符串參數)

Using drDataReader As IDataReader = _db.ExecuteReader("usp_get_systemsetting", "ORSIniPath") 
    Dim iIndex As Int32 
    While (drDataReader.Read()) 
     iIndex = drDataReader.GetOrdinal("SETTING_CHAR") 
     If drDataReader.IsDBNull(iIndex) Then 
      g_sORSIniPath = "" 
     Else 
      g_sORSIniPath = drDataReader.GetString(i) 
     End If 
    End While 
End Using 
相關問題