簡體   English   中英

如何使用c#從postgresql數據庫中檢索雙數組?

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

我使用C#返回雙數組並編寫以下代碼,但我在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
                    {

                    }
                }
            }

我怎么解決這個問題?

我找不到像Convert.ToDouble[]這樣的方法。 請閱讀: https//msdn.microsoft.com/en-us/library/system.convert.todouble(v=vs.110).aspx

首先,如果row["fcth"]是數組,則可以轉換為List<>Array

這個時候,你應該這樣:

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

這個例子中, rows["fcth"] = "1, 4, 4, 7"將返回數組double類型。

其次,如果你只想將字符串轉換為double。

你可以改為:

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

要么

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM