嗨,我一直有与标题所说的相同的错误。我不知道为什么会出错。我还是新手,所以,我不确定如何解决这个问题。如果有人可以帮助我,我将不胜感激,如果可能请提供一些需要更换的代码。谢谢。
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;
}
}
}
答案 0 :(得分:4)
SqlDataReader
用于读取您的数据 - 您无法将其传递给Convert.ToDateTime并希望获得最佳效果。
首先你要调用myReader.Read()
并检查它是否返回true(即你有一行数据)。
然后,您可以调用Convert.ToDateTime(myReader[0])
从数据读取器中取出第一个字段并将其转换为日期。
答案 1 :(得分:2)
这正是错误所说的。您无法将SqlDataReader转换为DateTime。如果只想查询单个值,则应使用:
cmd2.ExecuteScalar();
如果您要检索单个值,我建议您在查询中使用TOP 1
:
SELECT TOP 1 DISTINCT loanUpdateDate
另请注意,如果未找到任何值,ExecuteScalar()
可以返回DbNull.Value
,因此请务必在尝试将值转换为任何值之前进行空检查。