c# - 08P01 : insufficient data left in message for Nullable DateTime

标签 c# npgsql

我有一个数据库表,其中有一列定义为没有时区的时间戳。现在,在我的 C# 应用程序中,当我尝试使用 NpgSql BeginBinaryImport 在该列中插入空值时,它会给出如下错误消息:

08P01: insufficient data left in message

下面是我尝试执行的代码:

static void Main(string[] args)
{
    BulkInsert();
}

private static void BulkInsert()
{

    DataTable table = new DataTable();
    table.Columns.Add("firstname", typeof(String));
    table.Columns.Add("lastname", typeof(String));
    table.Columns.Add("logdatetime", typeof(DateTime));
    table.Columns.Add("status", typeof(int));
    table.Columns.Add("id", typeof(long));

    var dataRow = table.NewRow();
    dataRow["firstname"] = "MyFirstName";
    dataRow["lastname"] = "MyLastName";
    dataRow["logdatetime"] = DBNull.Value;
    dataRow["status"] = 1;
    dataRow["id"] = 10;
    table.Rows.Add(dataRow);

    var data = new DataAccess();

    using (var npgsqlConn = new NpgsqlConnection([ConnectionString]))
    {
        npgsqlConn.Open();
        var commandFormat = string.Format(CultureInfo.InvariantCulture, "COPY {0} {1} FROM STDIN BINARY", "logging.testtable", "(firstName,LastName,logdatetime,status,id)");
        using (var writer = npgsqlConn.BeginBinaryImport(commandFormat))
        {
            foreach (DataRow item in dataTable.Rows)
            {
                writer.StartRow();
                foreach (var item1 in item.ItemArray)
                {
                     writer.Write(item1);
                }

            }
        }

        npgsqlConn.Close();
}

最佳答案

问题是您尝试写入的DBNull.Value - Npgsql 不支持以这种方式写入空值。要写入 null,您需要使用 WriteNull() 方法。

我可以让 Npgsql 接受 DBNull.Value,但仅限于 Write() 的重载,它也接受 NpgsqlDbType(因为 Npgsql 必须写入数据类型,对于 DBNull.Value,我们不知道那是什么)。

编辑:已完成此操作,请参阅 https://github.com/npgsql/npgsql/issues/1122 .

关于c# - 08P01 : insufficient data left in message for Nullable DateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37431054/

相关文章:

c# - 开始中级 C# 类(class),重点放在 UML 上……您对经验丰富的建议的最佳建议?

asp.net - 消息 "28000: no pg_hba.conf entry for host\"xx.xxx.xxx.xxxx\", user\"用户”,数据库\"databasename\",SSL 关闭”

sql - 如何在 PostgreSql 中插入一条记录并返回新的 id 作为输出参数

c++ - 如何在 Visual Studio 2017 中为 C++ 安装 npgsql

c# - Entity Framework 7 中表和属性的名称不区分大小写

c# - 将 ObservableCollection 绑定(bind)到 ListBox 的选定项

C# 用户控件设计时序列化

c# - 为什么HttpContext.AcceptWebSocketRequest函数获取实例会报错?

c# - 多窗口问题 - C# WPF

c# - SqlBuilder 返回错误结果