如何向 Sqlcommand.Parameters 添加数字?

发布于 2024-08-03 23:17:37 字数 1432 浏览 3 评论 0原文

这是我的方法:

public void EjecutarGuardar(string ProcedimientoAlmacenado, object[] Parametros)
        {
            SqlConnection Connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

            SqlCommand Command = Connection.CreateCommand();
            Command.CommandText = ProcedimientoAlmacenado;
            Command.CommandType = CommandType.StoredProcedure;
            foreach (object X in Parametros)
            {
                Command.Parameters.Add(X);
            }            

            Connection.Open();
            Command.ExecuteNonQuery();
            Connection.Close();

            Connection.Dispose();
        }

假设我向对象数组 PARAMETROS 添加了一个 int ,当它到达 foreach 语句时,我收到错误:

仅限 SqlParameterCollection 接受非空 SqlParameter 类型 对象,而不是 Int32 对象。

那么,如何在此类之外加载所有参数,然后将它们全部放入通用数组中,并将其传递给此方法以发挥其魔力。有什么帮助吗?

编辑:朋友给我发了这个代码,它可以工作吗?我无法理解它在做什么。 :S

protected void CargarParametros(SqlCommand Com, System.Object[] Args)
        {                
            for (int i = 1; i < Com.Parameters.Count; i++)
            {
                SqlParameter P = (SqlParameter)Com.Parameters[i];
                if (i <= Args.Length )
                    P.Value = Args[i - 1];
                else
                    P.Value = null;
            }
        }

Here's my method:

public void EjecutarGuardar(string ProcedimientoAlmacenado, object[] Parametros)
        {
            SqlConnection Connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

            SqlCommand Command = Connection.CreateCommand();
            Command.CommandText = ProcedimientoAlmacenado;
            Command.CommandType = CommandType.StoredProcedure;
            foreach (object X in Parametros)
            {
                Command.Parameters.Add(X);
            }            

            Connection.Open();
            Command.ExecuteNonQuery();
            Connection.Close();

            Connection.Dispose();
        }

Say I added an int to my object array PARAMETROS, when it reaches the foreach statement I get an error:

The SqlParameterCollection only
accepts non-null SqlParameter type
objects, not Int32 objects.

So, how can I load all of my parameters outside of this class, and then place them all into a generic array, and pass it on to this method to do it's magic. Any help?

Edit: A friend sent me this code, would it work? I cant understand what it's doing. :S

protected void CargarParametros(SqlCommand Com, System.Object[] Args)
        {                
            for (int i = 1; i < Com.Parameters.Count; i++)
            {
                SqlParameter P = (SqlParameter)Com.Parameters[i];
                if (i <= Args.Length )
                    P.Value = Args[i - 1];
                else
                    P.Value = null;
            }
        }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

飘过的浮云 2024-08-10 23:17:37

使用 AddWithValue 方法,

string []para={"@eno","@ename","@edate"};
object []val={11,"A","1-1-2002"};

System.Data.SqlClient.SqlConnection cn = new System.Data.SqlClient.SqlConnection(@"");
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandText = "proc_name";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = cn;
for(int i=0;i<para.Length;i++){
  cmd.Parameters.AddWithValue(para[i], val[i]);
}

cn.Open();
cmd.ExecuteNonQuery();
cn.Close();

Use AddWithValue method,

string []para={"@eno","@ename","@edate"};
object []val={11,"A","1-1-2002"};

System.Data.SqlClient.SqlConnection cn = new System.Data.SqlClient.SqlConnection(@"");
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandText = "proc_name";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = cn;
for(int i=0;i<para.Length;i++){
  cmd.Parameters.AddWithValue(para[i], val[i]);
}

cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
香橙ぽ 2024-08-10 23:17:37

您的 SqlCommand 包装存储过程。为了调用它,您需要为传入或传出存储过程的每个参数创建一个 SqlParameter 实例。您不能只是简单地添加您的值 - ADO.NET 如何知道将哪个值分配给哪个参数?

每个 SqlParameter 包含以下内容:

  • 名称
  • 其数据类型
  • 可能有限制(大小、长度)
  • ,也可能有

因此,在您的情况下,您的语句应该看起来像这样:

SqlCommand Command = Connection.CreateCommand();
Command.CommandText = ProcedimientoAlmacenado;
Command.CommandType = CommandType.StoredProcedure;

foreach (object X in Parametros)
{
    SqlParameter param = new SqlParameter();
    param.ParameterName = Parametros.Name;
    // you need to find a way to determine what DATATYPE the
    // parameter will hold - Int, VarChar etc.
    param.SqlDbType = SqlDbType.Int;  
    param.Value = Parametros.Value;

    Command.Parameters.Add(param);
}           

因此,仅仅添加值是行不通的 - 您需要捕获这些参数及其名称、数据类型、长度等及其值。

马克

Your SqlCommand wraps up the stored procedure. In order to call it, you will need to create an instance of a SqlParameter for each parameter that you pass into or get out of the stored procedure. You cannot just simply add your values - how would ADO.NET know which value to assign to which parameter??

Each SqlParameter contains things like:

  • a name
  • its datatype
  • possibly restrictions (on size, length)
  • and possibly a value

So in your case, your statement should look something like this:

SqlCommand Command = Connection.CreateCommand();
Command.CommandText = ProcedimientoAlmacenado;
Command.CommandType = CommandType.StoredProcedure;

foreach (object X in Parametros)
{
    SqlParameter param = new SqlParameter();
    param.ParameterName = Parametros.Name;
    // you need to find a way to determine what DATATYPE the
    // parameter will hold - Int, VarChar etc.
    param.SqlDbType = SqlDbType.Int;  
    param.Value = Parametros.Value;

    Command.Parameters.Add(param);
}           

So, just adding values isn't going to work - you need to capture those parameters with their name, data type, length etc. and their values.

Marc

屋顶上的小猫咪 2024-08-10 23:17:37

您需要执行以下操作:

Sql 命令示例:

"SELECT * FROM YourTable WHERE FirstColumn = @YourParameterID;"

要为此命令添加参数:

Command.Parameters.Add(new SqlParameter("@YourParameterID", SqlDbType.Int).Value = X);

You need to do this:

Sql command example:

"SELECT * FROM YourTable WHERE FirstColumn = @YourParameterID;"

To add a parameter for this command:

Command.Parameters.Add(new SqlParameter("@YourParameterID", SqlDbType.Int).Value = X);
一张白纸 2024-08-10 23:17:37

我不是专家,但我想你应该命名你的参数;因此,您应该考虑拥有一个键值对数组,而不是仅仅拥有一个对象数组。

然后,您应该看一下 SqlParameter 构造函数之一: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparameter.sqlparameter.aspx

I'm not an expert, but I guess you should name your parameters; so instead of just having an array of object, you should consider having an array of key-value pairs.

Then, you should take a look at one of SqlParameter constructors: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparameter.sqlparameter.aspx

您还可以使用缩写版本。如果您这样做,ADO.NET 将知道它是一个数字,并将插入正确的数据类型:

Command.Parameters.Add(new SqlParameter("@YourParameterID", 4));

等等。

此外,请确保您没有将 NULL 插入到 NOT NULL 数据字段中,并且可以隐式转换为 SqlParameter 类型。

You can also use an abbreviated version. ADO.NET will know it's a number and will insert the proper datatype if you do this:

Command.Parameters.Add(new SqlParameter("@YourParameterID", 4));

etc.

Also, make sure you're not inserting a NULL into a NOT NULL data field, and is implicitly castable to type SqlParameter.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文