0

I have this problem reading "character varying" field data through a C# program from a PostgreSQL version 12 database table using npgsql. This is the code I use:

   NpgsqlDataSource DataSource = NpgsqlDataSource.Create(connectionString);
   NpgsqlCommand command = DataSource.CreateCommand("SET client_encoding = 'UTF8'");
   command.ExecuteNonQuery();

   command = DataSource.CreateCommand(this.Config.PostgreSQL_CommandString);
       int righe= command.ExecuteNonQuery();
       NpgsqlDataReader reader = command.ExecuteReader();
       while (reader.Read())
       {
           var v = reader.GetValue(1);
       }

The field contains, for example, the value ""Stanley Kubrick"" and what is read by the program (v variable) is "1\0\0\0\u00042\0\0\0\u0004T\0\0\0p".

I have already tried modifying the encode/decode and installing the latest versions of the dlls, but the result does not change. I would expect to be able to read the data correctly in readable format.

Do you have any suggestions? Thanks

12
  • have you tried configuring this on the connection-string instead (;Client Encoding=UTF8)? if the provider doesn't know that you've changed the encoding, it could do incorrect things Commented Jan 2, 2024 at 15:26
  • Yes, the result is always the same. Commented Jan 2, 2024 at 16:05
  • Why do you call ExecuteNonQuery() before ExeuteReader? Commented Jan 2, 2024 at 16:33
  • There should be nothing to read after executing a non-query. You would think that would cause an error, rather that gibberish, though. Commented Jan 2, 2024 at 16:37
  • It's left over from one of my tests to give me the number of lines. As you can see, I then execute a new query with ExecuteReader. Even if I remove the ExecuteNonQuery the result does not change. I get the correct number of rows and fields, but in the fields I find the data written in the format I reported. If I analyze the type of field I get that: reader.GetFieldType(<field>) => String reader.GetPostgresType(<field>) => character varying So the data structure is correct, but the conversion from "character varying" to "String" is not done correctly. Commented Jan 2, 2024 at 17:25

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.