简体   繁体   English

将2D数组从C#传递到Postgresql函数

[英]Pass 2D array from C# to Postgresql function

Here is postgresql running query with pg admin iii. 这是使用pg admin iii运行的postgresql查询。 (Below query working fine with pg admin and it is returning result set without any issue) (下面的查询与pg admin一起正常工作,并且返回结果集没有任何问题)

select * from  pg_sp_getmainrates_11(9,10,array[[5,10,10,10],[30,20,15,16]]);

Here is parameter declaration of pg function. 这是pg函数的参数声明。

CREATE OR REPLACE FUNCTION pg_sp_getmainrates_11(
    IN fromcountryid integer,
    IN tocountryid integer,    
    IN alldimensions_we_le_he_wi double precision[]
   )

-- My logic is going here

But when passing array using C# code, it is returning error when executing the query. 但是,当使用C#代码传递数组时,执行查询时将返回错误。

Exeption attributes 样本属性

Basemessage : syntax error at or near "," 基本消息:“,”或附近的语法错误

ErrorSql : SELECT * FROM pg_sp_getmainrates_11(9,10,System.Double[,]) ErrorSql:SELECT * FROM pg_sp_getmainrates_11(9,10,System.Double [,])

Here is my C# code. 这是我的C#代码。

   double[,] codes = new double[,]
    {
        { 5,10,10,10},{ 30,20,15,16}
    };

  string quy = "pg_sp_getmainrates_11(" + FromCountryId +
                               "," + ToCountryId +
                               "," + codes + ")";

        NpgsqlCommand command = new NpgsqlCommand(quy, conn);
        command.CommandType = CommandType.StoredProcedure;
        NpgsqlDataReader dr = command.ExecuteReader();

I need a small direction to pass an array (like above) to my postgresql function. 我需要一个小的方向来将数组(如上)传递给我的postgresql函数。

Up to now I found a solution for this. 到目前为止,我已经找到了解决方案。 (Don't know whether this is the optimum solution) The simple thing to send parameter as string. (不知道这是否是最佳解决方案)将参数作为字符串发送很简单。 With my C# code I make some string like below. 使用我的C#代码,我编写了如下所示的字符串。

String arr = "array[[5,10,10,10],[30,20,15,16]]";

This arr will be passed as query parameter. 此arr将作为查询参数传递。

string quy = "pg_sp_getmainrates_11(" + FromCountryId +
                               "," + ToCountryId +
                               "," + arr+ ")";

Above solution works fine. 上述解决方案工作正常。

You can use using Newtonsoft.Json; 您可以使用using Newtonsoft.Json;来使用using Newtonsoft.Json; and insert your array like the following: 并按如下所示插入数组:

string[][] arr = {{5, 10, 10, 10},{30, 20, 15, 16}};
var arrayOutput = JsonConvert.SerializeObject(arr);

try
{
    string sql1 = "INSERT INTO tbt(img, fcth, dev) VALUES (ARRAY'" + arrayOutput + "')";
    dbcmd.CommandText = sql1;
    cmd.ExecuteNonQuery();
}

catch (NpgsqlException ex)
{
    if (ex.Data == null)
    {
        throw;
    }

    else
    {
    }

}

This example Just for array column. 此示例仅用于数组列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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