Npgsql 中的 InvalidCastException
我的问题是:我想通过对两个日期之间的货币类型列进行求和来写入结果。
代码:
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"));
}
My question is:I want to write the result by suming a column which is money type between two dates.
Code:
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"));
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试转换为十进制而不是双精度。
“money”类型的 Postgres 文档 建议输出的格式为“$1,000.00”(取决于区域设置),在这种情况下,您需要解析返回值并在转换之前删除标点符号。
另外,如果这是生产代码,您需要对 SQL 进行参数化,而不是在其中附加参数值,否则您很容易受到潜在的 SQL 注入攻击,并且还可能出现性能问题。
有一些讨论 .NET 中货币数据类型的线程可能也会有所帮助。这是一个:有人知道 .NET 中的货币类型吗?
Try casting to decimal instead of double.
The Postgres documentation for the "money" type suggests that the output is in the form "$1,000.00" (locale-dependent), in which case you'd need to parse the return value and remove the punctuation before casting.
Also, if that's production code, you'll want to parameterize your SQL instead of appending parameter values in there, otherwise you're open to potential SQL injection attacks and may have performance problems as well.
There are a few threads discussing currency data types in .NET which might also be helpful. Here's one: Does anyone know of a money type in .NET?