1

嗨,我一直遇到与标题相同的错误。我不知道为什么出了什么问题。我还是新手,所以我不确定如何解决这个问题。如果有人可以帮助我,我将不胜感激,如果可能,请提供一些需要替换的代码。谢谢你。


public DataTable getAllLoanInfoDT()
{ 
    using (SqlConnection conn = new SqlConnection(connString))
    {
        SqlCommand cmd2 = new SqlCommand();
        cmd2.Connection = conn;
        // cmd.CommandType = CommandType.StoredProcedure;
        cmd2.CommandText = "SELECT DISTINCT loanUpdateDate FROM LoanPortfolio WHERE (custID LIKE 'OH00002') AND (loanType LIKE 'Personal Loan')"; 
        cmd2.Parameters.AddWithValue("@custID", "OH00002");
        cmd2.Parameters.AddWithValue("@loanType", "Personal Loan");
        conn.Open();
        SqlDataReader myReader = cmd2.ExecuteReader();
        DateTime loanUpdateDate = Convert.ToDateTime(myReader);
        DateTime currDateTime = DateTime.Now;

        int loanToBeAdded = (((currDateTime.Year - loanUpdateDate.Year) * 12) + currDateTime.Month - loanUpdateDate.Month) * 500;
        if (loanToBeAdded > 0)
        {
            String sql = "UPDATE LoanPortfolio SET loanPaid = loanPaid + " + loanToBeAdded.ToString() + ", loanUpdateDate = " + DateTime.Now.ToString();
            sql += " WHERE (loanType LIKE 'Personal Loan') AND (custID LIKE 'OH00002')";

            //Execute the above query here
        }
        conn.Close();

        using (SqlDataAdapter dAd = new SqlDataAdapter("SELECT * FROM LoanPortfolio where custID like 'OH00002'", conn))
        {
            DataTable dTable = new DataTable();
            dAd.Fill(dTable);
            return dTable;
        }
    }
}
4

2 回答 2

4

ASqlDataReader用于读取您的数据 - 您不能只将其传递给 Convert.ToDateTime 并希望最好。

首先,您将调用myReader.Read()并检查它是否返回 true(即您有一行数据)。

然后,您将调用Convert.ToDateTime(myReader[0])从数据读取器中获取第一个字段并将其转换为日期。

于 2013-07-29T15:48:18.843 回答
2

这正是错误所说的。不能将 SqlDataReader 转换为 DateTime。如果您只想查询单个值,则应使用:

cmd2.ExecuteScalar();

如果您要检索单个值,我建议TOP 1您也可以在查询中使用:

SELECT TOP 1 DISTINCT loanUpdateDate 

另请注意,如果未找到任何值,则ExecuteScalar()可以返回DbNull.Value,因此请务必在尝试将值转换为任何值之前进行空检查。

于 2013-07-29T15:47:52.993 回答