0

I want save 2-dim array in postgresql some like this: int[,] arr = {{1, 2}, {3, 4}};

I am using the following sql statement which is working fine to 1-dim array, but it is not work for 2-dim array.

try
{
    string sql1 = "INSERT INTO tbtest(col) VALUES (ARRAY[" + string.Join(", ", arr) + "])";

    dbcmd.CommandText = sql1;
    dbcmd.ExecuteNonQuery();
}
catch (NpgsqlException ex)
{
    if (ex.Data == null)
    {
        throw;
    }
    else
    {

    }
}

How can I do this?

2

1 Answer 1

0

Try this method

 int[,] arr = { { 1, 2 }, { 3, 4 } };   
 var arrayOutput = JsonConvert.SerializeObject(arr);
 string query = "INSERT INTO tbtest(col) VALUES (ARRAY" + arrayOutput + ")";

Output

INSERT INTO tbtest(col) VALUES (ARRAY[[1,2],[3,4]])

Sign up to request clarification or add additional context in comments.

7 Comments

what was the error in JsonConvert? You need to add NewtonSoft.Json from Nuget package .
error: the name JsonConver does not exit in the current context
you need to add NewtonSoft.Json Dll.
I did not find NewtonSoft.Json Dll Net 4.5. Can you send the link
you can add this package using Nuget
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.