将SQLreader转换为float?

时间:2013-08-01 10:26:51

标签: c# asp.net

我一直试图找回贷款金额,并希望它是浮动的。但是,loanAmount返回值0.0。顺便说一句,sql语句只返回一个值。请帮忙吗?

SqlCommand cmd5 = new SqlCommand();
        cmd4.Connection = conn;
        cmd4.CommandText = "SELECT loanAmount FROM LoanPortfolio WHERE custID='" + custIDs + "' AND loanType LIKE 'Personal Loan'";
        conn.Open();
        float loanAmount = 0.0F;
        SqlDataReader amountLoan = cmd4.ExecuteReader();
        while (amountLoan.Read())
        {
            loanAmount = float.Parse(amountLoan.ToString());
            break;
        }
        conn.Close();

3 个答案:

答案 0 :(得分:4)

如果您选择的是单个值,请使用ExecuteScalar():

float loanAmount = Convert.ToFloat(cmd4.ExecuteScalar());

希望这有帮助。

答案 1 :(得分:1)

  

btw sql语句只返回一个值

您仍需要指定列:

 loanAmount = float.Parse(amountLoan[0].ToString());

有更好的方法来获取该值,取决于列类型等。

答案 2 :(得分:0)

从复数变量名称(custIDs)中,我假设您传入了多个ID,并且为了调试/测试目的插入了break。将命令文本修改为:

cmd4.CommandText = "SELECT loanAmount FROM LoanPortfolio WHERE custID IN (" + custIDs + ") AND loanType LIKE 'Personal Loan'";

确保custId是客户ID的逗号分隔值字符串。 您应该选择阅读器中的第一列:

float.Parse(amountLoan[0].ToString())

或使用SqlDataReader.GetFloat method

此外,您需要将返回值存储在某种集合(数组,列表等)中。现在,即使查询返回多条记录,您也只能获取最后一条记录的值。