我使用IDataReader来调用没有参数的存储过程。当参数存在时,我没有找到如何执行此操作的示例。 IDataReader是否处理存储过程的参数?
请举例说明。
答案 0 :(得分: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 :(得分:7)
如果你使用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
}
}
答案 2 :(得分: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();
答案 3 :(得分: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