繁体   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