我正在尝试用C#读取SQL中的列类型‘unique标识符’。
SqlCommand myCommand = new SqlCommand();
myCommand.CommandText = "SELECT templatename, subject, bodyhtml, sender, emailTemplateBodyFields.fieldid FROM emailTemplates left join emailtemplaterecipients on emailtemplates.emailtemplateid = emailtemplaterecipients.emailtemplateid left join emailTemplateBodyFields on emailtemplates.emailtemplateid = emailTemplateBodyFields.emailtemplateid WHERE emailtemplates.emailtemplateid = " + selectedEmailTemplateID;
myCommand.Connection = connection;
SqlDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
NewTemplateName = myReader.GetString(0);
NewSubject = myReader.GetString(1);
NewBodyHTML = myReader.GetString(2);
NewRecipients = myReader.GetString(3);
myRecipientList.Add(NewRecipients);
Guid tempGUID = myReader.GetGuid(4);
NewBodyFields = Convert.ToString(tempGUID);
myBodyList.Add(NewBodyFields);但是我得到了一个空值异常,数据是空的。
Guid tempGUID = myReader.GetGuid(4);在Server中运行该语句时,该列没有空值。
请建议如何从本专栏中检索信息。
谢谢。
发布于 2012-11-15 11:08:25
您正在使用LEFT JOIN到emailTemplateBodyFields。如果该表中不存在相应的记录,则可能导致结果集中的空值,即使对于表中确实存在的记录而言,fieldid从未为空。您可以检查IsDBNull的结果:对于您获得异常的行,您将看到它返回true。
要修复它,要么重新工作查询以确保没有空值,要么准备在调用IsDBNull之前通过检查GetGuid来处理空值。
关于您的代码的两条侧注释:
selectedEmailTemplateID来自用户输入吗?如果恶意用户决定设置为"1; DROP TABLE emailTemplates",怎么办?那么您的查询将做什么呢?使用参数。using关键字使得这非常容易,因此这里没有任何理由不这样做。https://stackoverflow.com/questions/13396114
复制相似问题