-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
67 lines (60 loc) · 2.2 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// See https://aka.ms/new-console-template for more information
using System.Data;
using System.Text;
using Npgsql;
const string connectionString = @"Host=localhost; Database=test_db; Username=postgres; Password=postgres";
using var connection = new NpgsqlConnection(connectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
using (var tableCommand = new NpgsqlCommand(@"CREATE TABLE blob (id integer, bytes bytea)", connection))
{
tableCommand.ExecuteNonQuery();
}
using (var directWriteCommand = new NpgsqlCommand(@"INSERT INTO blob VALUES (1, convert_to('a', 'LATIN1'))", connection))
{
directWriteCommand.ExecuteNonQuery();
}
using (var directReadCommand = new NpgsqlCommand(@"SELECT bytes FROM blob WHERE id = 1", connection))
{
using var directReadReader = directReadCommand.ExecuteReader();
directReadReader.Read();
using var directReadStream = directReadReader.GetStream(0);
using var directReadStreamReader = new StreamReader(directReadStream);
var s = directReadStreamReader.ReadToEnd();
if (s == "a")
{
Console.WriteLine($"✔ Got correct data: '{s}'");
}
else
{
Console.WriteLine($"❌ Got invalid data: '{s}'");
}
}
using (var writeCommand = new NpgsqlCommand(@"INSERT INTO blob VALUES (2, @bytes)", connection))
{
using var stream = new MemoryStream(Encoding.UTF8.GetBytes("b"));
writeCommand.Parameters.Add(new NpgsqlParameter
{
DbType = DbType.Binary,
ParameterName = "@bytes",
Value = stream,
Size = -1,
});
writeCommand.ExecuteNonQuery();
}
using (var streamReadCommand = new NpgsqlCommand(@"SELECT bytes FROM blob WHERE id = 2", connection))
{
using var streamReadReader = streamReadCommand.ExecuteReader();
streamReadReader.Read();
using var streamReadStream = streamReadReader.GetStream(0);
using var streamReadStreamReader = new StreamReader(streamReadStream);
var s = streamReadStreamReader.ReadToEnd();
if (s == "b")
{
Console.WriteLine($"✔ Got correct data: '{s}'");
}
else
{
Console.WriteLine($"❌ Got invalid data: '{s}'");
}
}