/*
CREATE TABLE test.array_test
(
f_array text[][]
)
WITH (OIDS=FALSE);
ALTER TABLE test.array_test OWNER TO postgres;
INSERT INTO test.array_test VALUES ('{{"elem11", "elem12", "elem13"},{"elem21","elem22", "elem23"}}')
*/
public void PgSqlArrayManipulation() {
object[] elements = new object[6] { 2, 43, 4, 5, 6, 10 };
int rank = 2;
int dimension1 = 3;
int dimension2 = 2;
// One way to initialize PgSqlArray
PgSqlArray array1 = new PgSqlArray(elements, PgSqlType.Int, rank, dimension1, dimension2);
Console.WriteLine(array1.ToString()); // {{2,43},{4,5},{6,2}}
// Another way to initialize PgSqlArray
PgSqlArray array2 = new PgSqlArray(PgSqlType.Int, rank, dimension1, dimension2);
int inc = 0;
// Set elements of the array
for (int i = 1; i < array2.GetLength(1) + 1; i++)
for (int j = 1; j < array2.GetLength(2) + 1; j++) {
array2.SetValue(elements[inc++], i, j);
}
Console.WriteLine(array2); // {{2,43},{4,5},{6,2}}
// Get all elements
foreach (PgSqlArray subArr in array1)
foreach (int elem in subArr)
Console.Write(elem + ",");
Console.WriteLine();
// Get one element
int number = (int)array1[3, 2];
Console.WriteLine(number); // Outputs 10
}
public void GetPgSqlArray(PgSqlConnection connection) {
PgSqlCommand cmd = new PgSqlCommand();
cmd.Connection = connection;
cmd.CommandText = "SELECT f_array FROM test.array_test";
using (PgSqlDataReader reader = cmd.ExecuteReader()) {
while (reader.Read()) {
PgSqlArray array = reader.GetPgSqlArray(0);
Console.WriteLine(array);
}
}
}
public void UsingPgSqlArrayAsParameter(PgSqlConnection connection) {
PgSqlCommand cmd = new PgSqlCommand();
cmd.Connection = connection;
cmd.CommandText = "INSERT INTO test.array_test(f_array) VALUES(:p)";
// creates array {{elem11,elem12,elem13},{elem21,elem22,elem23}}
// rank = 2, dimensions = {2,3}
object[] elements = new object[] { "elem11","elem12","elem13","elem21","elem22","elem23" };
PgSqlArray array = new PgSqlArray(elements, PgSqlType.Text, 2, 2, 3);
PgSqlParameter param = new PgSqlParameter("p", PgSqlType.Array);
param.Value = array;
cmd.Parameters.Add(param);
cmd.ExecuteNonQuery();
}