Npgsql字符串转换为数字类型

4

这是代码:

autoInsert.Parameters.Add(new NpgsqlParameter("price", NpgsqlDbType.Numeric));
autoInsert.Parameters[0].Value = txt_price.Text;
        con.Open();
        autoInsert.ExecuteNonQuery();
        con.Close();

当我执行查询时,显示错误:“输入字符串格式不正确。” 如何将该字符串转换为数字。 txt_price是文本框。

txt_price.Text 的内容是什么? - Davide Piras
2个回答

3
autoInsert.Parameters[0].Value = ConvertToInt32(txt_price.Text); 

2
在传递 Numeric 时,您向 Npgsql 确保您正在传递一个数字。然后您传递了一个字符串。
如果由于其他代码,您已经确定 txt_price 中有一个十进制值,并且不可能有其他内容,则使用以下方法:
autoInsert.Parameters[0].Value = decimal.Parse(txt_price.Text);

否则,在执行其他操作之前,将其与代码结合起来以确保此操作:
decimal price;
if(!decimal.TryParse(txt_price.Text, out price))
{
   //code to display message that txt_price doesn't have a valid value.
   return;
}
using(var con = /*your code that constructs the connection*/)
{
  using(autoInsert = /*your code that returns to command*/)
  {
    autoInsert.Parameters.Add(new NpgsqlParameter("price", NpgsqlDbType.Numeric));
    autoInsert.Parameters[0].Value = price;
    con.Open();
    autoInsert.ExecuteNonQuery();
    con.Close();
  }
}

autoInsert.Parameters["price"].Value = price; 可以使代码更易读,也更易于维护。 - TomEberhard

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接