创建动态SQL DbParameter值

时间:2011-08-18 20:22:45

标签: c# sql

首次使用者 - 希望这种格式正确:

我想知道我是否可以在ParamaterName上创建SQL DbParameter值。

我目前的代码是:

DbCommand dbCommand = SqlDb.GetStoredProcCommand(uspCommand);
DbParameter ProcessedFileName = dbCommand.CreateParameter();
ProcessedFileName.DbType = DbType.String;
ProcessedFileName.ParameterName = "@FileName";
ProcessedFileName.Value = pstrProcessedFileName;
dbCommand.Parameters.Add(ProcessedFileName);

我想补充一下:

ProcessedFileName.ParameterName = "@FileName1";
ProcessedFileName.ParameterName = "@FileName2";
ProcessedFileName.ParameterName = "@FileName3";
ProcessedFileName.ParameterName = "@FileName4";

@FileNames来自数组。

5 个答案:

答案 0 :(得分:6)

这样的事情应该有效:

DbCommand dbCommand = SqlDb.GetStoredProcCommand(uspCommand);

foreach(String param in MyParameters)
{
   DbParameter ProcessedFileName = dbCommand.CreateParameter();
   ProcessedFileName.DbType = DbType.String;
   ProcessedFileName.ParameterName = param;
   ProcessedFileName.Value = pstrProcessedFileName;
   dbCommand.Parameters.Add(ProcessedFileName);
}

答案 1 :(得分:2)

最好的方法是将它们放在字典中,因为你还需要值

Dictionary<string, string> params = new Dictionary<string,string>();

并根据需要添加许多

params.Add("@FileName1", "my_filename")

等...

然后

foreach(var param in params)
   dbCommand.Parameters.AddWithValue(param.Key, param.Value);

答案 2 :(得分:0)

答案 3 :(得分:0)

重构为DbCommand的扩展,fieldName也没有@,所以你需要传递@或:前缀,而fieldValue被设置为对象类型(不仅仅是字符串)。

public static class DbCommandExtensions
{
    public static void AddParam(this DbCommand dbCommand, string fieldName, object fieldValue)
    {
        string fieldNameParameter = fieldName;

        DbParameter dbParameter = dbCommand.CreateParameter();
        dbParameter.ParameterName = fieldNameParameter;
        dbParameter.Value = fieldValue;
        dbCommand.Parameters.Add(dbParameter);
    }
}

答案 4 :(得分:0)

创建动态SQL DbParameter值

当您要创建有动态数据库的项目时,这非常有用,或者将来您可能要迁移/切换数据库。

这是一步一步的解决方案

步骤1)创建参数结构

  public struct Parameter
    {
        public string ParameterName { get; set; }
        public ParameterDirection Direction { get; set; }
        public DbType DbType { get; set; }
        public object Value { get; set; }
        public string SourceColumn { get; set; }
        public int Size { get; set; }
    }

步骤2)创建数据库处理类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Data.Common;
using MySql.Data.MySqlClient;
using MySql.Data;
using Oracle.DataAccess;
using Oracle.DataAccess.Client;

 public class DBManagement  
    {
        string connectionStr;
        DbConnection con;
        DbCommand cmd;
        DbDataAdapter AD;
        DataSet ds;
        DbParameter[] sp;
        IDBManagement Iobj = null;
        public DBManagement()
        {
            this.Initialize();
        }

 void Initialize()
        {
            try
            {

                switch (ConfigurationManager.AppSettings["ActiveDatabase"].ToUpper())
                {
                    case "MSSQL":
                        connectionStr = ConfigurationManager.ConnectionStrings["MSSQLConnectionString"].ConnectionString;
                        con = new SqlConnection();
                        cmd = new SqlCommand();
                        AD = new SqlDataAdapter();
                        break;
                    case "ORACLE":
                        connectionStr = ConfigurationManager.ConnectionStrings["OracleConnectionString"].ConnectionString;
                        con = new OracleConnection();
                        cmd = new OracleCommand();
                        AD = new OracleDataAdapter();
                        break;
                    case "MYSQL":
                        connectionStr = ConfigurationManager.ConnectionStrings["MYSQLConnectionString"].ConnectionString;
                        con = new MySqlConnection();
                        cmd = new MySqlCommand();
                        AD = new MySqlDataAdapter();
                        break;
                    default:

                        break;
                }

                con.ConnectionString = connectionStr;
                cmd.Connection = con;
            }
            catch (Exception ex)
            {

            }
        }

        public DataSet ExecuteProcedure(string procName, CommandType cmdType, Parameter[] DBParameters = null)
        {
            try
            {
                cmd.CommandText = procName;
                cmd.CommandType = cmdType;

                cmd.Parameters.Clear();

                if (DBParameters != null && DBParameters.Length > 0)
                { 
                    sp = DBParameters.ToParamerArray(cmd);  
                    cmd.Parameters.AddRange(sp); 
                }
                ds = new DataSet();
                AD.SelectCommand = cmd;
                AD.Fill(ds);
                return ds;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
}

步骤3)按照数据库转换参数

public static partial class GlobalExtensionFunctions 
    {
        public static DbParameter[] ToParamerArray(this Parameter[] parameters,DbCommand cmd)
        {
            DbParameter[] sp = new DbParameter[parameters.Length]; 
            int i = 0;
            foreach (Parameter parameter in parameters)
            {
               // DbParameter p = cmd.CreateParameter();
                sp[i] = cmd.CreateParameter();
                sp[i].ParameterName = parameter.ParameterName;
                sp[i].Value = parameter.Value;
                sp[i].Direction = string.IsNullOrEmpty(Convert.ToString(parameter.Direction))  || parameter.Direction==0 ? ParameterDirection.Input : parameter.Direction;
                sp[i].DbType = parameter.DbType;
                sp[i].SourceColumn = parameter.SourceColumn;
                sp[i].Size = parameter.Size;
                i++;
            }
            return sp;
        }
    }

步骤4)获取数据

 DBManagement c = new DBManagement();
public DataSet GetGetTestList(int testId)
        {
            Parameter[] p = new Parameter[1]; 

            p[0].ParameterName = "@TestId";
            p[0].Value = testId;
            p[0].DbType = DbType.Int32;

            return c.ExecuteProcedure(Procedures.TestDetails, CommandType.StoredProcedure,p);
        }

现在使用数据集或数据表并享受! :)