简体   繁体   中英

how to retrieve double array from postgresql database using c#?

I am using C# to return double array and write the following code but I got error in Convert.ToDouble[] :

            string connectionString = "Server=localhost;port=5432;Database=dbtest;User ID=postgres;Password=123";
        NpgsqlConnection dbcon = new NpgsqlConnection(connectionString);
        dbcon.Open();
        NpgsqlCommand dbcmd = dbcon.CreateCommand();

        string sql = "SELECT fcth FROM test01";
        NpgsqlDataAdapter da = new NpgsqlDataAdapter(sql, dbcon);

        NpgsqlCommand command = new NpgsqlCommand("SELECT fcth FROM tbl");
        NpgsqlDataReader dr = dbcmd.ExecuteReader();

        DataSet ds = new DataSet();
        da.Fill(ds, "tbl");
        List<double[]> arr = new List<double[]>();

        foreach (DataRow row in ds.Tables["tbl"].Rows)
        {
            dr.Read();

            arr.Add(Convert.ToDouble[](row["fcth"].ToString()));  
        }

        for (int j = 0; j < arr.Count; j++)
        {
                try
                {
                    string sql2 = "INSERT INTO tbl2(fh) VALUES ('" + arr[j] + "')";

                    dbcmd.CommandText = sql2;
                    dbcmd.ExecuteNonQuery();
                }
                catch (NpgsqlException ex)
                {

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

                    }
                }
            }

How can I solve this problem?

I can't find any method like Convert.ToDouble[] . Please read: https://msdn.microsoft.com/en-us/library/system.convert.todouble(v=vs.110).aspx .

First, you can convert to List<> or Array if row["fcth"] is array.

At this time, you should to like this:

Array.ConvertAll(row["fcth"].Split(','), Double.Parse);

This only example, rows["fcth"] = "1, 4, 4, 7" will return array double type.

Second, if you only want to convert string to double.

You can change to:

arr.Add((Double)row["fcth"]);

or

arr.Add(double.TryParse(row["fcth"]); .

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