2011-07-30 45 views
1

enter image description hereInvalidCastException的Npgsql的中

我的問題是:我想suming列這是兩個日期之間的資金類型寫的結果。

代碼:

using (NpgsqlConnection b = new NpgsqlConnection("Server=127.0.0.1;Port=5432;User Id=postgres;Password=xxxxxxxx;DataBase=deneme;")) 
     { 
      try 
      { 
       b.Open(); 
       NpgsqlCommand c = new NpgsqlCommand("SELECT SUM(tutar) FROM market where tarih between '" + dateTimePicker1.Value + "' and '" + dateTimePicker2.Value + "'", b); 
       double toplam = ((double)c.ExecuteScalar()); 
       b.Close(); 
       b.Dispose(); 
       MessageBox.Show(toplam.ToString("n")); 
      } 

回答

2

試着鑄造成十進制,而不是雙。

The Postgres documentation for the "money" type表明輸出格式爲「$ 1,000.00」(取決於語言環境),在這種情況下,您需要解析返回值並在投射前刪除標點符號。另外,如果這是生產代碼,那麼您需要參數化您的SQL,而不是在那裏添加參數值,否則您可能面臨潛在的SQL注入攻擊,並且可能還存在性能問題。

有幾個線程討論.NET中的貨幣數據類型,這可能也是有幫助的。這裏有一個:Does anyone know of a money type in .NET?