You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SqlCommand中定义参数类型并后续设置参数值?

能否在SqlCommand初始化时定义参数类型,之后再设置参数值?

当然可以实现你想要的写法!你之前尝试的语法问题在于SqlParameterCollection的初始化器不能直接用"@参数名" as SqlDbType这种简写,得明确创建SqlParameter实例来指定类型,之后就能单独给参数赋值了。

修正后的完整可运行代码

try {
    // Open connection
    conexion.Open();
    // Start transaction
    SqlTransaction transaccion = conexion.BeginTransaction();
    // Initialize command with parameter types defined upfront
    SqlCommand comandoAEjecutar = new SqlCommand {
        Connection = conexion,
        Transaction = transaccion,
        CommandText = @"
            INSERT INTO [dbo].[table_battery] ([capacity], [description], [image], [price])
            VALUES (@capacity, @description, @fileContent, @price)
        ",
        // Use SqlParameter instances to define parameter names and types
        Parameters = {
            new SqlParameter("@capacity", SqlDbType.Int),
            new SqlParameter("@description", SqlDbType.VarChar), // Optional: add length like SqlDbType.VarChar, 500
            new SqlParameter("@fileContent", SqlDbType.VarBinary),
            new SqlParameter("@price", SqlDbType.Float)
        }
    };

    int capacity = 50;
    string descr = "Funciona2";
    float price = 70;
    string path = @"C:\Users\Juan\Desktop\Ingeniería Informática\2 año\2º Cuatrimestre\Programación Visual Avanzada\ProyectoFinal\AJMobile\AJMobile\src\images\Battery\baterry_4000.png";
    byte[] fileContent = File.ReadAllBytes(path);

    // Assign values to pre-defined parameters
    comandoAEjecutar.Parameters["@capacity"].Value = capacity;
    comandoAEjecutar.Parameters["@description"].Value = descr;
    comandoAEjecutar.Parameters["@fileContent"].Value = fileContent;
    comandoAEjecutar.Parameters["@price"].Value = price;

    int numeroFilasAfectadas = comandoAEjecutar.ExecuteNonQuery();
    
    // Don't forget to commit the transaction!
    transaccion.Commit();
}
catch (Exception ex) {
    // Rollback transaction if something goes wrong
    transaccion?.Rollback();
    // Handle exception (e.g. logging, user notification)
    Console.WriteLine($"Error: {ex.Message}");
}

关键说明

  1. 语法修正原因:Parameters是SqlParameterCollection类型,它的集合初始化器只接受SqlParameter对象,不能直接用键值对映射。必须显式创建SqlParameter实例来绑定参数名和数据类型。
  2. 可选优化:对于VarChar这类可变长度类型,建议指定最大长度(比如new SqlParameter("@description", SqlDbType.VarChar, 500)),这能避免潜在的性能损耗或类型不匹配问题。
  3. 事务补充:你的原代码缺少事务提交和异常回滚逻辑,上面的示例补充了这部分,防止出现未提交的事务导致数据不一致。

内容的提问来源于stack exchange,提问作者JuMoGar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:35:31