c#-4.0 - 如何在 C# 中将 SQLiteDataReader 值转换为 float

标签 c#-4.0 casting sqlite floating-point

我正在努力解决一个小问题:SqliteDataReader 的转换值转换为 float .我正在展示我是如何尝试转换的。

Pricing pricing = null;
SQLiteConnection con = new SQLiteConnection(thisApp.dbConnectionString);
try
{
   string _sql = "select * from pricing where id=@id";
   SQLiteCommand command = new SQLiteCommand(_sql, con);
   command.Parameters.AddWithValue("id", myid);
   con.Open();
   SQLiteDataReader reader = command.ExecuteReader();
   if (reader.HasRows)
   {
      while (reader.Read())
      {
          pricing = new Pricing()
          {
              // "ActualPrice" in my model and "actual_price" in sqlite db are Float type.
              // But here i am getting error saying cast is not allowed
              // It tried one more way as well but didn't work.
              ActualPrice = Convert.ToInt32(reader["actual_price"])
              // OR
              ActualPrice = (float) Convert.ToInt32(reader["actual_price"])
          };
      }
   }               
 }
 catch
 {
 }
 finally
 {
    if (con.State != ConnectionState.Closed)
       con.Close();
 }
 return pricing;

你能帮我如何从 reader["actual_price] 获取值吗?进入我的属性(property)ActualPrice ?

最佳答案

我的建议是

首先尝试将列值读取为字符串,例如

   Pricing pricing = new Pricing();
    string string_val=convert.ToString(reader["actual_price"]);

然后使用 TryParse

如果您的属性是 double 类型,请使用 double.TryParse
float _val=0;

float.Tryparse(string_val,out _val);

然后分配模型属性,如
pricing.ActualPrice =_val;

进行字符串转换然后 Tryparse 的好处是它可以帮助您处理空值异常

可能这也可以通过其他一些更简单的方式来完成

关于c#-4.0 - 如何在 C# 中将 SQLiteDataReader 值转换为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35597099/

相关文章:

c# - 将重复列折叠到子列表中

时间:2019-01-17 标签:c#evalfunction

c# - 在 C# 中转换时应该使用 (ObjectType) 还是 'as ObjectType'?

sql - 嵌套的 SQL 查询搜索错误的表 (postgreSQL)

javascript - JSON.parse、JS 类型转换和 revivers

java - JPA 返回空结果列表,而 DB 返回行集

java - SqlJet 事务误用错误

c# - 在调用 Read() 之前访问字段的尝试无效。代码不工作

c#-4.0 - 如何在 C# WPF 应用程序中拖放图像文件

sql - 对嵌套集中的 sibling 进行排序