首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何封装存储过程调用

问如何封装存储过程调用
EN

Stack Overflow用户
提问于 2009-08-27 10:28:10
回答 1查看 937关注 0票数 3

我有一个用来做数据库操作的DAO类。我有很多从不同方法/函数调用的存储过程。在每个函数/方法中,我都编写了一行代码来为SP添加参数值。有没有什么方法可以封装它,这样所有的函数/方法都可以调用这个封装的功能来将参数传递给不同的存储过程。我相信你们中的许多人都做过类似的事情。基本上,我试图避免多余的语句来将参数添加到参数集合中。

(我使用的是C# 3.5)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2009-08-27 10:46:23

可能是这样的:

代码语言:javascript
复制
public static IDataReader GetDataReader(string connectionStringKey, string storedProcedure, Dictionary<string, object> parameters) {
    try {
        SqlCommand command = GetCommandWithConnection(connectionStringKey);
        command.CommandText = storedProcedure;
        command.CommandType = CommandType.StoredProcedure;
        foreach (var parameter in parameters ?? new Dictionary<string, object>())
            command.Parameters.AddWithValue(parameter.Key, parameter.Value);
        command.Connection.Open();
        return command.ExecuteReader();
    }
    catch (Exception e) {
        Log.Error(string.Format("Error in GetDataReader, executing sp: {0}", storedProcedure), e);
        throw;
    }     
}
private static SqlCommand GetCommandWithConnection(string connectionStringKey) {
    return new SqlConnection(GetConnectionString(connectionStringKey)).CreateCommand();
}
private static string GetConnectionString(string connectionStringKey) {
    return ConfigurationManager.ConnectionStrings[connectionStringKey].ToString();
}

Edit:因为你已经添加了注释来说明你需要支持输出参数,下面是来自同一个dal类的另一个方法:

代码语言:javascript
复制
public static T GetScalar<T>(string connectionStringKey, string storedProcedure, Parameters parameters) {
    try {
        List<Parameter> outs = null;
        SqlCommand command = GetCommandWithConnection(connectionStringKey);
        command.CommandText = storedProcedure;
        command.CommandType = CommandType.StoredProcedure;
        if (parameters != null) {
            outs = parameters.FindAll(p => p.Direction != ParameterDirection.Input);
            parameters.ForEach(p => command.Parameters.AddWithValue(p.Key, p.Value).Direction = p.Direction);
        }
        command.Connection.Open();
        object o = command.ExecuteScalar();
        T result = (o != null) ? (T)o : default(T);
        if (outs != null && outs.Count > 0) {
            foreach (Parameter parameter in outs) {
                SqlParameter sqlParameter = command.Parameters[parameter.Key];
                parameters[parameter.Key] = (sqlParameter.Value == DBNull.Value) ? null : sqlParameter.Value;
            }
        }
        command.Connection.Close();
        if (o == null && (typeof(T) == typeof(int)) && parameters != null && parameters.ContainsKey("RowCount"))
            result = (T)parameters["RowCount"];
        return result;
    }
    catch (Exception e) {
        Log.Error(String.Format("Error in GetScalar<{0}>, executing sp: {1}", typeof(T).Name, storedProcedure), e);
        throw;
    }
}

和支持的参数类:

代码语言:javascript
复制
public class Parameter{
    public string Key { get; private set; }
    public object Value { get; protected internal set; }
    public ParameterDirection Direction { get; protected internal set; }
    public Parameter(string key, object value) : this(key, value, ParameterDirection.Input) { }
    public Parameter(string key, object value, ParameterDirection direction){
        Key = key;
        Value = value;
        Direction = direction;
    }
}
public class Parameters : List<Parameter>{
    public Parameters() { }
    public Parameters(object o){
        Populate(o);
    }
    public void Add(string key, object value){
        if (ContainsKey(key))
            throw new Exception("Parameter with the specified key already exists.");
        Add(new Parameter(key, value));
    }
    public void Add(string key, object value, ParameterDirection direction){
        if (ContainsKey(key))
            throw new Exception("Parameter with the specified key already exists.");
        Add(new Parameter(key, value, direction));
    }
    public bool ContainsKey(string key){
        return (Find(p => p.Key == key) != null);
    }
    protected internal int GetIndex(string key){
        int? index = null;
        for (int i = 0; i < Count; i++){
            if (this[i].Key == key){
                index = i;
                break;
            }
        }
        if (index == null)
            throw new IndexOutOfRangeException("Parameter with the specified key does not exist.");
        return (int)index;
    }
    public object this[string key]{
        get { return this[GetIndex(key)].Value; }
        set { this[GetIndex(key)].Value = value; }
    }
    private void Populate<T>(T obj){
        foreach (KeyValuePair<string, object> pair in new ObjectProperties(obj, BindingFlags.Public | BindingFlags.Instance))
            Add(pair.Key, pair.Value);
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1340184

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档