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

使用C#向DB2 iSeries批量插入数据时仅插入NULL值的问题排查

批量插入DB2数据库出现全NULL值的问题解决

问题场景

创建的DB2表结构:

CREATE TABLE tsdta.ftestbk1
(
   NUM numeric(8,0),
   TEXT varchar(30)
)

使用C#代码批量插入数据后,表中所有记录均为NULL值:

NUM   | TEXT
------------
<null> |<null>
<null> |<null>
<null> |<null>
<null> |<null>
<null> |<null>

错误原因

  1. 参数操作逻辑错误:调用DeriveParameters()后,系统已根据SQL语句生成对应参数对象,循环中重复用Add()添加同名参数,导致参数列表混乱,实际执行时使用的是最初派生的空参数。
  2. 批量执行方法错误:添加批量命令后需调用ExecuteBatch()执行,而非ExecuteNonQuery(),后者无法正确触发批量操作逻辑。

修正后的代码

using IBM.Data.DB2.iSeries;
using System.Data;

// ...

using (iDB2Connection connection = new iDB2Connection("xxx"))
{
    string sql = @"insert into tsdta.ftestbk1 
                   values
                   (
                      @num,
                      @text
                   )";
    connection.Open();
    iDB2Command command = connection.CreateCommand();
    command.CommandType = CommandType.Text;
    command.CommandText = sql;
    command.Prepare();
    command.DeriveParameters();

    for (int i = 0; i < 5; i++)
    {
        // 重置已有参数的值,而非重复添加新参数
        command.Parameters["@num"].Value = i;
        command.Parameters["@text"].Value = $"some text for {i}";
        command.AddBatch();
    }

    // 执行批量命令并获取每条操作的受影响行数
    int[] rowsAffected = command.ExecuteBatch();
    // connection.Close()可省略,using块会自动释放连接资源
}

额外优化方案

若不需要自动派生参数,可手动定义参数类型,避免DeriveParameters()的潜在问题:

// 替换command.DeriveParameters(),手动定义参数
command.Parameters.Add("@num", iDB2DbType.iDB2Numeric);
command.Parameters.Add("@text", iDB2DbType.iDB2VarChar, 30);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 05:25:16