【发布时间】:2012-04-13 02:17:13
【问题描述】:
我有一堂课,代码如下
public cCase(string pCaseNo, string pMode)
{
if (pMode == "new")
{
this._caseNo = Validate_CaseNo(pCaseNo);
}
if (pMode == "existing")
{
try
{
int intValidatedCaseNo = Validate_CaseNo(pCaseNo);
string sqlText = "SELECT * FROM tblCases WHERE CaseNo = @CaseNo;";
string strConnection = cConnectionString.BuildConnectionString();
SqlConnection linkToDB = new SqlConnection(strConnection);
linkToDB.Open();
SqlCommand sqlCom = new SqlCommand(sqlText, linkToDB);
sqlCom.Parameters.Add("@CaseNo", SqlDbType.Int);
sqlCom.Parameters["@CaseNo"].Value = intValidatedCaseNo;
SqlDataReader caseReader = sqlCom.ExecuteReader();
if (caseReader.HasRows)
while (caseReader.Read())
{
this._claimant = caseReader["Claimant"].ToString();
this._defendant = caseReader["Defendant"].ToString();
this._caseType = caseReader["CaseType"].ToString();
this._occupation = caseReader["Occupation"].ToString();
this._doa = (DateTime?)caseReader["DOA"];
this._dateClosed = (DateTime?)caseReader["DateClosed"];
this._dateSettled = (DateTime?)caseReader["DateSettled"];
this._dateInstructed = (DateTime?)caseReader["DateInstructed"];
this._status = caseReader["Status"].ToString();
this._instructionType = caseReader["InstructionType"].ToString();
this._feeEstimate = (decimal?)caseReader["FeeEstimate"];
this._amountClaimed = (decimal?)caseReader["AmountClaimed"];
this._amountSettled = (decimal?)caseReader["AmountSettled"];
this._caseManager = caseReader["CaseManager"].ToString();
}
caseReader.Close();
linkToDB.Close();
linkToDB.Dispose();
}
catch (Exception eX)
{
throw new Exception("Error finding case" + Environment.NewLine + eX.Message);
}
}
}
但是日期时间呢?转换失败并出现“无效转换”。 我检查了 SQL 数据库并且该字段正在存储有效日期 所以我不知道为什么,当我通过 DataReader 将信息提取到我的应用程序中时,日期时间字段会导致无效转换。
请帮忙。
【问题讨论】:
-
caseReader持有什么类型? -
您的一个 DateTime 字段可能包含一个 DBNull - 据我所知,您不能直接从 DBNull 转换为 Nullable 类型。然而,这种情况有扩展。
-
以及关于空值的其他答案 - 您说该字段正在存储有效日期,但它是否使用适当的数据类型存储它们(例如
datetime、datetime2或date) ? -
似乎 dateTime 字段的数据类型之一是 VARCHAR(MAX) 或 NTEXT。请检查SQL表中的类型,你可能会得到一些线索。