-5

我正在尝试创建一个通用方法来调用存储过程

我想通过数组传入参数

目前我无法将参数添加到 SqlCommand

这就是我到目前为止所拥有的

任何人都可以建议

谢谢

西蒙

调用方法

string[] paramNames = new string[1];
paramNames[0] = "@date = 2012-1-1";
string err="";


WriteToDatabase("exec LoadData", CommandType.StoredProcedure, paramNames, out err);

方法

public static bool WriteToDatabase(
        string sql,
        CommandType commandType,
        string[] paramNames,
        out string errorText)
    {
        bool success = false;
        errorText = "";
        try
        {
            using (SqlConnection connection = new SqlConnection(ConnectionString))
            {
               connection.Open(); 
                List<SqlParameter> parameters = new List<SqlParameter>();

                foreach (string paramName in paramNames)
                {
                    parameters.Add(new SqlParameter() { ParameterName = paramName });
                }

                using (SqlCommand command = new SqlCommand()
                {
                    Connection = connection,
                    CommandText = sql,
                    CommandType = commandType,
                    Parameters = parameters

                })
                 command.ExecuteNonQuery();  

                 connection.Close();
            }


        }
        catch (SqlException sex)
        {
            log.Error("QueryDatabase SQLexception:" + sex.Message);
        }
        catch (Exception ex)
        {
            log.Error("QueryDatabase exception:" + ex.Message);
        }
        return success;
    }
4

3 回答 3

2

这是我不久前开设的一堂课。它很容易使用:

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Xml;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Text;

namespace NESCTC.Data
{   
    public class DataAccess : IDisposable
    {
        #region declarations

        private SqlCommand _cmd;
        private string _SqlConnString;

        #endregion

        #region constructors

        public DataAccess(string ConnectionString)
        {
            _cmd = new SqlCommand();
            _cmd.CommandTimeout = 240;
            _SqlConnString = ConnectionString;
        }

        #endregion

        #region IDisposable implementation

        ~DataAccess()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);            
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                _cmd.Connection.Dispose();
                _cmd.Dispose();
            }
        }

        #endregion

        #region data retrieval methods

        public DataTable ExecReturnDataTable()
        {
            using (var conn = new SqlConnection(this.ConnectionString))
            {
                try
                {
                    PrepareCommandForExecution(conn);
                    using (SqlDataAdapter adap = new SqlDataAdapter(_cmd))
                    {
                        DataTable dt = new DataTable();
                        adap.Fill(dt);
                        return dt;
                    }
                }
                finally
                {
                    _cmd.Connection.Close();
                }
            }
        }                

        public object ExecScalar()
        {
            using (var conn = new SqlConnection(this.ConnectionString))
            {
                try
                {
                    PrepareCommandForExecution(conn);
                    return _cmd.ExecuteScalar();
                }
                finally
                {
                    _cmd.Connection.Close();
                }
            }
        }    

        #endregion

        #region data insert and update methods

        public void ExecNonQuery()
        {
            using (var conn = new SqlConnection(this.ConnectionString))
            {
                try
                {
                    PrepareCommandForExecution(conn);
                    _cmd.ExecuteNonQuery();
                }
                finally
                {
                    _cmd.Connection.Close();
                }
            }
        }

        #endregion

        #region helper methods

        public void AddParm(string ParameterName, SqlDbType ParameterType, object Value)
        { _cmd.Parameters.Add(ParameterName, ParameterType).Value = Value; }

        private SqlCommand PrepareCommandForExecution(SqlConnection conn)
        {
            try
            {
                _cmd.Connection = conn;
                _cmd.CommandType = CommandType.StoredProcedure;
                _cmd.CommandTimeout = this.CommandTimeout;
                _cmd.Connection.Open();

                return _cmd;
            }
            finally
            {
                _cmd.Connection.Close();
            }
        }

        #endregion

        #region properties

        public int CommandTimeout
        {
            get { return _cmd.CommandTimeout; }
            set { _cmd.CommandTimeout = value; }
        }

        public string ProcedureName
        {
            get { return _cmd.CommandText; }
            set { _cmd.CommandText = value; }
        }

        public string ConnectionString
        {
            get { return _SqlConnString; }
            set { _SqlConnString = value; }
        }

        #endregion
    }
}

以下是如何使用它的示例:

public void UpdateWorkOrder(int workOrderID, int paymentTermTypeID, string acceptedBy, string lastIssuedBy)
{
    using (var data = new DataAccess(this.ConnectionString))
    {
        data.ProcedureName = "UpdateWorkOrderDetails";
        data.AddParm("@WorkOrderID", SqlDbType.Int, workOrderID);
        data.AddParm("@PaymentTermTypeID", SqlDbType.Int, paymentTermTypeID);
        data.AddParm("@AcceptedBy", SqlDbType.VarChar, acceptedBy);
        data.AddParm("@LastIssuedBy", SqlDbType.VarChar, lastIssuedBy);
        data.ExecNonQuery();
    }
}

public DataTable GetWorkOrder(int workOrderID)
{
    using (var data = new DataAccess(this.ConnectionString))
    {
        data.ProcedureName = "GetWorkOrder";
        data.AddParm("@WorkOrderID", SqlDbType.Int, workOrderID);
        return data.ExecReturnDataTable();
    }
}
于 2012-04-10T15:46:42.797 回答
0

您必须分别指定参数的名称和值。你有不同的选择来做到这一点。参数集合有一个方法

public SqlParameter AddWithValue(string parameterName, object value)

如果你想使用它,你必须将它们都提供给你的方法

public static bool WriteToDatabase(
    string sql,
    CommandType commandType, 
    string[] paramNames,    
    object[] paramValues,    
    out string errorText)    
{
    ...
    for (int i = 0; i < paramNames.Length; i++) {
        command.Parameters.AddWithValue(paramNames[i], paramValues[i]);
    }
    ...
}
于 2012-04-10T15:47:57.103 回答
0

这个页面很有帮助http://csharp-station.com/Tutorial/AdoDotNet/Lesson01 看看,很多例子!

于 2013-03-13T23:19:02.790 回答