简体   繁体   中英

How to store 2D array in postgresql using C#?

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?

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]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM