Postgres bytea column is returning string (char array) instead of byte array

后端 未结 2 628
南笙
南笙 2021-01-03 07:07

I have been using C# to write a concrete provider implementation for our product for different databases. W/out getting into details, one of the columns is of byte array typ

相关标签:
2条回答
  • 2021-01-03 07:46

    Ran the same problem, but managed to solve the problem without having to resort to changing drivers.

    PHP documentation has a good description of what's happening, Postgres is returning escaped data. Check your output against an ASCII table, when you see 92 48 ... it's the text lead in to an octal escape sequence, \0xx, just like PHP describes.

    Postgres's binary data type explains the output escaped octets. Fret not, there are code examples.

    The solution is to tell Postgres how to bytea output is escaped, which can be either escape or hex. In this case issue the following to Postgres via psql to match your data:

    ALTER DATABASE yourdb SET BYTEA_OUTPUT TO 'escape';
    
    0 讨论(0)
  • 2021-01-03 07:48

    In Npgsql there is NpgsqlDataReader class to retrieve inserted rows, e.g:

    NpgsqlConnection conn = new NpgsqlConnection(connStr);
    conn.Open();
    
    NpgsqlCommand insertCmd =
        new NpgsqlCommand("INSERT INTO binaryData (data) VALUES(:dataParam)", conn);
    NpgsqlParameter param = new NpgsqlParameter("dataParam", NpgsqlDbType.Bytea);
    
    byte[] inputBytes = BitConverter.GetBytes((int)0);
    Console.Write("Input:");
    foreach (byte b in inputBytes)
        Console.Write(" {0}", b);
    Console.WriteLine();
    
    param.Value = inputBytes;
    insertCmd.Parameters.Add(param);
    insertCmd.ExecuteNonQuery();
    
    NpgsqlCommand selectCmd = new NpgsqlCommand("SELECT data FROM binaryData", conn);
    NpgsqlDataReader dr = selectCmd.ExecuteReader();
    if(dr.Read())
    {
        Console.Write("Output:");
        byte[] result = (byte[])dr[0];
        foreach(byte b in result)
            Console.Write(" {0}", b);
        Console.WriteLine();
    }
    
    conn.Close();
    

    Result from C# app:

    Input: 0 0 0 0
    Output: 0 0 0 0
    

    Result from pgAdmin:

    "\000\000\000\000"
    

    EDIT:

    I found explanation why you getting:

    92 48 48 48 48 48 48 48 48
    

    I checked my code with previous version Npgsql2.0.10-bin-ms.net3.5sp1.zip and get above result (of course pgAdmin returns \000\000\000\000), so I think that best what you can do is to use another version without this bug.

    ANSWER: User higher version of Npgsql than 2.0.10

    0 讨论(0)
提交回复
热议问题